file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2022-03-05
*/
// Verified using https://dapp.tools
// hevm: flattened sources of /nix/store/n0zrh7hav4swn38ckv0y2panmrlaxy1s-geb-fsm/dapp/geb-fsm/src/DSM.sol
pragma solidity =0.6.7;
////// /nix/store/3d3msxain9q01swpn63dsh9wl2hsal24-geb-treasury-reimbursement/dapp/geb-treasury-reimbursement/src/math/GebMath.sol
/* pragma solidity 0.6.7; */
contract GebMath {
uint256 public constant RAY = 10 ** 27;
uint256 public constant WAD = 10 ** 18;
function ray(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 9);
}
function rad(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 27);
}
function minimum(uint x, uint y) public pure returns (uint z) {
z = (x <= y) ? x : y;
}
function addition(uint x, uint y) public pure returns (uint z) {
z = x + y;
require(z >= x, "uint-uint-add-overflow");
}
function subtract(uint x, uint y) public pure returns (uint z) {
z = x - y;
require(z <= x, "uint-uint-sub-underflow");
}
function multiply(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "uint-uint-mul-overflow");
}
function rmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / RAY;
}
function rdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, RAY) / y;
}
function wdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, WAD) / y;
}
function wmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / WAD;
}
function rpower(uint x, uint n, uint base) public pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
}
////// /nix/store/3d3msxain9q01swpn63dsh9wl2hsal24-geb-treasury-reimbursement/dapp/geb-treasury-reimbursement/src/reimbursement/NoSetupNoAuthIncreasingTreasuryReimbursement.sol
/* pragma solidity 0.6.7; */
/* import "../math/GebMath.sol"; */
abstract contract StabilityFeeTreasuryLike_2 {
function getAllowance(address) virtual external view returns (uint, uint);
function systemCoin() virtual external view returns (address);
function pullFunds(address, address, uint) virtual external;
}
contract NoSetupNoAuthIncreasingTreasuryReimbursement is GebMath {
// --- Variables ---
// Starting reward for the fee receiver/keeper
uint256 public baseUpdateCallerReward; // [wad]
// Max possible reward for the fee receiver/keeper
uint256 public maxUpdateCallerReward; // [wad]
// Max delay taken into consideration when calculating the adjusted reward
uint256 public maxRewardIncreaseDelay; // [seconds]
// Rate applied to baseUpdateCallerReward every extra second passed beyond a certain point (e.g next time when a specific function needs to be called)
uint256 public perSecondCallerRewardIncrease; // [ray]
// SF treasury
StabilityFeeTreasuryLike_2 public treasury;
// --- Events ---
event ModifyParameters(
bytes32 parameter,
address addr
);
event ModifyParameters(
bytes32 parameter,
uint256 val
);
event FailRewardCaller(bytes revertReason, address feeReceiver, uint256 amount);
constructor() public {
maxRewardIncreaseDelay = uint(-1);
}
// --- Boolean Logic ---
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
// --- Treasury ---
/**
* @notice This returns the stability fee treasury allowance for this contract by taking the minimum between the per block and the total allowances
**/
function treasuryAllowance() public view returns (uint256) {
(uint total, uint perBlock) = treasury.getAllowance(address(this));
return minimum(total, perBlock);
}
/*
* @notice Get the SF reward that can be sent to a function caller right now
* @param timeOfLastUpdate The last time when the function that the treasury pays for has been updated
* @param defaultDelayBetweenCalls Enforced delay between calls to the function for which the treasury reimburses callers
*/
function getCallerReward(uint256 timeOfLastUpdate, uint256 defaultDelayBetweenCalls) public view returns (uint256) {
// If the rewards are null or if the time of the last update is in the future or present, return 0
bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);
if (either(timeOfLastUpdate >= now, nullRewards)) return 0;
// If the time elapsed is smaller than defaultDelayBetweenCalls or if the base reward is zero, return 0
uint256 timeElapsed = (timeOfLastUpdate == 0) ? defaultDelayBetweenCalls : subtract(now, timeOfLastUpdate);
if (either(timeElapsed < defaultDelayBetweenCalls, baseUpdateCallerReward == 0)) {
return 0;
}
// If too much time elapsed, return the max reward
uint256 adjustedTime = subtract(timeElapsed, defaultDelayBetweenCalls);
uint256 maxPossibleReward = minimum(maxUpdateCallerReward, treasuryAllowance() / RAY);
if (adjustedTime > maxRewardIncreaseDelay) {
return maxPossibleReward;
}
// Calculate the reward
uint256 calculatedReward = baseUpdateCallerReward;
if (adjustedTime > 0) {
calculatedReward = rmultiply(rpower(perSecondCallerRewardIncrease, adjustedTime, RAY), calculatedReward);
}
// If the reward is higher than max, set it to max
if (calculatedReward > maxPossibleReward) {
calculatedReward = maxPossibleReward;
}
return calculatedReward;
}
/**
* @notice Send a stability fee reward to an address
* @param proposedFeeReceiver The SF receiver
* @param reward The system coin amount to send
**/
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal {
// If the receiver is the treasury itself or if the treasury is null or if the reward is zero, return
if (address(treasury) == proposedFeeReceiver) return;
if (either(address(treasury) == address(0), reward == 0)) return;
// Determine the actual receiver and send funds
address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver;
try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {}
catch(bytes memory revertReason) {
emit FailRewardCaller(revertReason, finalFeeReceiver, reward);
}
}
}
////// /nix/store/n0zrh7hav4swn38ckv0y2panmrlaxy1s-geb-fsm/dapp/geb-fsm/src/DSM.sol
/* pragma solidity 0.6.7; */
/* import "geb-treasury-reimbursement/reimbursement/NoSetupNoAuthIncreasingTreasuryReimbursement.sol"; */
abstract contract DSValueLike_1 {
function getResultWithValidity() virtual external view returns (uint256, bool);
}
abstract contract FSMWrapperLike_1 {
function renumerateCaller(address) virtual external;
}
contract DSM {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "DSM/account-not-authorized");
_;
}
// --- Stop ---
uint256 public stopped;
modifier stoppable { require(stopped == 0, "DSM/is-stopped"); _; }
// --- Variables ---
address public priceSource;
uint16 public updateDelay = ONE_HOUR; // [seconds]
uint64 public lastUpdateTime; // [timestamp]
uint256 public newPriceDeviation; // [wad]
uint16 constant ONE_HOUR = uint16(3600); // [seconds]
// --- Structs ---
struct Feed {
uint128 value;
uint128 isValid;
}
Feed currentFeed;
Feed nextFeed;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 parameter, uint256 val);
event ModifyParameters(bytes32 parameter, address val);
event Start();
event Stop();
event ChangePriceSource(address priceSource);
event ChangeDeviation(uint deviation);
event ChangeDelay(uint16 delay);
event RestartValue();
event UpdateResult(uint256 newMedian, uint256 lastUpdateTime);
constructor (address priceSource_, uint256 deviation) public {
require(deviation > 0 && deviation < WAD, "DSM/invalid-deviation");
authorizedAccounts[msg.sender] = 1;
priceSource = priceSource_;
newPriceDeviation = deviation;
if (priceSource != address(0)) {
// Read from the median
(uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate();
// If the price is valid, update state
if (hasValidValue) {
nextFeed = Feed(uint128(uint(priceFeedValue)), 1);
currentFeed = nextFeed;
lastUpdateTime = latestUpdateTime(currentTime());
emit UpdateResult(uint(currentFeed.value), lastUpdateTime);
}
}
emit AddAuthorization(msg.sender);
emit ChangePriceSource(priceSource);
emit ChangeDeviation(deviation);
}
// --- DSM Specific Math ---
uint256 private constant WAD = 10 ** 18;
function add(uint64 x, uint64 y) internal pure returns (uint64 z) {
z = x + y;
require(z >= x);
}
function sub(uint x, uint y) private pure returns (uint z) {
z = x - y;
require(z <= x, "uint-uint-sub-underflow");
}
function mul(uint x, uint y) private pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "uint-uint-mul-overflow");
}
function wmul(uint x, uint y) private pure returns (uint z) {
z = mul(x, y) / WAD;
}
// --- Core Logic ---
/*
* @notify Stop the DSM
*/
function stop() external isAuthorized {
stopped = 1;
emit Stop();
}
/*
* @notify Start the DSM
*/
function start() external isAuthorized {
stopped = 0;
emit Start();
}
/*
* @notify Change the oracle from which the DSM reads
* @param priceSource_ The address of the oracle from which the DSM reads
*/
function changePriceSource(address priceSource_) external isAuthorized {
priceSource = priceSource_;
emit ChangePriceSource(priceSource);
}
/*
* @notify Helper that returns the current block timestamp
*/
function currentTime() internal view returns (uint) {
return block.timestamp;
}
/*
* @notify Return the latest update time
* @param timestamp Custom reference timestamp to determine the latest update time from
*/
function latestUpdateTime(uint timestamp) internal view returns (uint64) {
require(updateDelay != 0, "DSM/update-delay-is-zero");
return uint64(timestamp - (timestamp % updateDelay));
}
/*
* @notify Change the deviation supported for the next price
* @param deviation Allowed deviation for the next price compared to the current one
*/
function changeNextPriceDeviation(uint deviation) external isAuthorized {
require(deviation > 0 && deviation < WAD, "DSM/invalid-deviation");
newPriceDeviation = deviation;
emit ChangeDeviation(deviation);
}
/*
* @notify Change the delay between updates
* @param delay The new delay
*/
function changeDelay(uint16 delay) external isAuthorized {
require(delay > 0, "DSM/delay-is-zero");
updateDelay = delay;
emit ChangeDelay(updateDelay);
}
/*
* @notify Restart/set to zero the feeds stored in the DSM
*/
function restartValue() external isAuthorized {
currentFeed = nextFeed = Feed(0, 0);
stopped = 1;
emit RestartValue();
}
/*
* @notify View function that returns whether the delay between calls has been passed
*/
function passedDelay() public view returns (bool ok) {
return currentTime() >= uint(add(lastUpdateTime, uint64(updateDelay)));
}
/*
* @notify Update the price feeds inside the DSM
*/
function updateResult() virtual external stoppable {
// Check if the delay passed
require(passedDelay(), "DSM/not-passed");
// Read the price from the median
(uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate();
// If the value is valid, update storage
if (hasValidValue) {
// Update state
currentFeed.isValid = nextFeed.isValid;
currentFeed.value = getNextBoundedPrice();
nextFeed = Feed(uint128(priceFeedValue), 1);
lastUpdateTime = latestUpdateTime(currentTime());
// Emit event
emit UpdateResult(uint(currentFeed.value), lastUpdateTime);
}
}
// --- Getters ---
/*
* @notify Internal helper that reads a price and its validity from the priceSource
*/
function getPriceSourceUpdate() internal view returns (uint256, bool) {
try DSValueLike_1(priceSource).getResultWithValidity() returns (uint256 priceFeedValue, bool hasValidValue) {
return (priceFeedValue, hasValidValue);
}
catch(bytes memory) {
return (0, false);
}
}
/*
* @notify View function that returns what the next bounded price would be (taking into account the deviation set in this contract)
*/
function getNextBoundedPrice() public view returns (uint128 boundedPrice) {
boundedPrice = nextFeed.value;
if (currentFeed.value == 0) return boundedPrice;
uint128 lowerBound = uint128(wmul(uint(currentFeed.value), newPriceDeviation));
uint128 upperBound = uint128(wmul(uint(currentFeed.value), sub(mul(uint(2), WAD), newPriceDeviation)));
if (nextFeed.value < lowerBound) {
boundedPrice = lowerBound;
} else if (nextFeed.value > upperBound) {
boundedPrice = upperBound;
}
}
/*
* @notify Returns the lower bound for the upcoming price (taking into account the deviation var)
*/
function getNextPriceLowerBound() public view returns (uint128) {
return uint128(wmul(uint(currentFeed.value), newPriceDeviation));
}
/*
* @notify Returns the upper bound for the upcoming price (taking into account the deviation var)
*/
function getNextPriceUpperBound() public view returns (uint128) {
return uint128(wmul(uint(currentFeed.value), sub(mul(uint(2), WAD), newPriceDeviation)));
}
/*
* @notify Return the current feed value and its validity
*/
function getResultWithValidity() external view returns (uint256, bool) {
return (uint(currentFeed.value), currentFeed.isValid == 1);
}
/*
* @notify Return the next feed's value and its validity
*/
function getNextResultWithValidity() external view returns (uint256, bool) {
return (nextFeed.value, nextFeed.isValid == 1);
}
/*
* @notify Return the current feed's value only if it's valid, otherwise revert
*/
function read() external view returns (uint256) {
require(currentFeed.isValid == 1, "DSM/no-current-value");
return currentFeed.value;
}
}
contract SelfFundedDSM is DSM, NoSetupNoAuthIncreasingTreasuryReimbursement {
constructor (address priceSource_, uint256 deviation) public DSM(priceSource_, deviation) {}
// --- Administration ---
/*
* @notify Modify a uint256 parameter
* @param parameter The parameter name
* @param val The new value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized {
if (parameter == "baseUpdateCallerReward") {
require(val < maxUpdateCallerReward, "SelfFundedDSM/invalid-base-caller-reward");
baseUpdateCallerReward = val;
}
else if (parameter == "maxUpdateCallerReward") {
require(val >= baseUpdateCallerReward, "SelfFundedDSM/invalid-max-reward");
maxUpdateCallerReward = val;
}
else if (parameter == "perSecondCallerRewardIncrease") {
require(val >= RAY, "SelfFundedDSM/invalid-reward-increase");
perSecondCallerRewardIncrease = val;
}
else if (parameter == "maxRewardIncreaseDelay") {
require(val > 0, "SelfFundedDSM/invalid-max-increase-delay");
maxRewardIncreaseDelay = val;
}
else revert("SelfFundedDSM/modify-unrecognized-param");
emit ModifyParameters(parameter, val);
}
/*
* @notify Modify an address parameter
* @param parameter The parameter name
* @param val The new value for the parameter
*/
function modifyParameters(bytes32 parameter, address val) external isAuthorized {
if (parameter == "treasury") {
require(val != address(0), "SelfFundedDSM/invalid-treasury");
treasury = StabilityFeeTreasuryLike_2(val);
}
else revert("SelfFundedDSM/modify-unrecognized-param");
emit ModifyParameters(parameter, val);
}
// --- Core Logic ---
/*
* @notify Update the price feeds inside the DSM
*/
function updateResult() override external stoppable {
// Check if the delay passed
require(passedDelay(), "SelfFundedDSM/not-passed");
// Read the price from the median
(uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate();
// If the value is valid, update storage
if (hasValidValue) {
// Get the caller's reward
uint256 callerReward = getCallerReward(lastUpdateTime, updateDelay);
// Update state
currentFeed.isValid = nextFeed.isValid;
currentFeed.value = getNextBoundedPrice();
nextFeed = Feed(uint128(priceFeedValue), 1);
lastUpdateTime = latestUpdateTime(currentTime());
// Emit event
emit UpdateResult(uint(currentFeed.value), lastUpdateTime);
// Pay the caller
rewardCaller(msg.sender, callerReward);
}
}
}
contract ExternallyFundedDSM is DSM {
// --- Variables ---
// The wrapper for this DSM. It can relay treasury rewards
FSMWrapperLike_1 public fsmWrapper;
// --- Evemts ---
event FailRenumerateCaller(address wrapper, address caller);
constructor (address priceSource_, uint256 deviation) public DSM(priceSource_, deviation) {}
// --- Administration ---
/*
* @notify Modify an address parameter
* @param parameter The parameter name
* @param val The new value for the parameter
*/
function modifyParameters(bytes32 parameter, address val) external isAuthorized {
if (parameter == "fsmWrapper") {
require(val != address(0), "ExternallyFundedDSM/invalid-fsm-wrapper");
fsmWrapper = FSMWrapperLike_1(val);
}
else revert("ExternallyFundedDSM/modify-unrecognized-param");
emit ModifyParameters(parameter, val);
}
// --- Core Logic ---
/*
* @notify Update the price feeds inside the DSM
*/
function updateResult() override external stoppable {
// Check if the delay passed
require(passedDelay(), "ExternallyFundedDSM/not-passed");
// Check that the wrapper is set
require(address(fsmWrapper) != address(0), "ExternallyFundedDSM/null-wrapper");
// Read the price from the median
(uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate();
// If the value is valid, update storage
if (hasValidValue) {
// Update state
currentFeed.isValid = nextFeed.isValid;
currentFeed.value = getNextBoundedPrice();
nextFeed = Feed(uint128(priceFeedValue), 1);
lastUpdateTime = latestUpdateTime(currentTime());
// Emit event
emit UpdateResult(uint(currentFeed.value), lastUpdateTime);
// Pay the caller
try fsmWrapper.renumerateCaller(msg.sender) {}
catch(bytes memory revertReason) {
emit FailRenumerateCaller(address(fsmWrapper), msg.sender);
}
}
}
}
|
@notify Returns the upper bound for the upcoming price (taking into account the deviation var)/
|
function getNextPriceUpperBound() public view returns (uint128) {
return uint128(wmul(uint(currentFeed.value), sub(mul(uint(2), WAD), newPriceDeviation)));
}
| 7,649,374
|
//Address: 0xe68225eeaeae795bbfa3cebd1dfe422e1b17ce55
//Contract name: Raindrop
//Balance: 0 Ether
//Verification Date: 3/16/2018
//Transacion Count: 22
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Raindrop is Ownable {
// Event for when an address is authenticated
event AuthenticateEvent(
uint partnerId,
address indexed from,
uint value
);
// Event for when an address is whitelisted to authenticate
event WhitelistEvent(
uint partnerId,
address target,
bool whitelist
);
address public hydroContract = 0x0;
mapping (uint => mapping (address => bool)) public whitelist;
mapping (uint => mapping (address => partnerValues)) public partnerMap;
mapping (uint => mapping (address => hydroValues)) public hydroPartnerMap;
struct partnerValues {
uint value;
uint challenge;
}
struct hydroValues {
uint value;
uint timestamp;
}
function setHydroContractAddress(address _addr) public onlyOwner {
hydroContract = _addr;
}
/* Function to whitelist partner address. Can only be called by owner */
function whitelistAddress(address _target, bool _whitelistBool, uint _partnerId) public onlyOwner {
whitelist[_partnerId][_target] = _whitelistBool;
emit WhitelistEvent(_partnerId, _target, _whitelistBool);
}
/* Function to authenticate user
Restricted to whitelisted partners */
function authenticate(address _sender, uint _value, uint _challenge, uint _partnerId) public {
require(msg.sender == hydroContract);
require(whitelist[_partnerId][_sender]); // Make sure the sender is whitelisted
require(hydroPartnerMap[_partnerId][_sender].value == _value);
updatePartnerMap(_sender, _value, _challenge, _partnerId);
emit AuthenticateEvent(_partnerId, _sender, _value);
}
function checkForValidChallenge(address _sender, uint _partnerId) public view returns (uint value){
if (hydroPartnerMap[_partnerId][_sender].timestamp > block.timestamp){
return hydroPartnerMap[_partnerId][_sender].value;
}
return 1;
}
/* Function to update the hydroValuesMap. Called exclusively from the Hydro API */
function updateHydroMap(address _sender, uint _value, uint _partnerId) public onlyOwner {
hydroPartnerMap[_partnerId][_sender].value = _value;
hydroPartnerMap[_partnerId][_sender].timestamp = block.timestamp + 1 days;
}
/* Function called by Hydro API to check if the partner has validated
* The partners value and data must match and it must be less than a day since the last authentication
*/
function validateAuthentication(address _sender, uint _challenge, uint _partnerId) public constant returns (bool _isValid) {
if (partnerMap[_partnerId][_sender].value == hydroPartnerMap[_partnerId][_sender].value
&& block.timestamp < hydroPartnerMap[_partnerId][_sender].timestamp
&& partnerMap[_partnerId][_sender].challenge == _challenge) {
return true;
}
return false;
}
/* Function to update the partnerValuesMap with their amount and challenge string */
function updatePartnerMap(address _sender, uint _value, uint _challenge, uint _partnerId) internal {
partnerMap[_partnerId][_sender].value = _value;
partnerMap[_partnerId][_sender].challenge = _challenge;
}
}
|
Function to update the partnerValuesMap with their amount and challenge string /
|
function updatePartnerMap(address _sender, uint _value, uint _challenge, uint _partnerId) internal {
partnerMap[_partnerId][_sender].value = _value;
partnerMap[_partnerId][_sender].challenge = _challenge;
}
| 6,345,441
|
./full_match/80001/0x394954589BB3E6455A8424054e1E358a5bD1Dfc2/sources/project_/contracts/founders.sol
|
emit WithdrawEthFunds(_amount);
|
function withdrawEthFunds(uint256 _amount) public onlyOwner nonReentrant {
require(
_amount > 0 && _amount <= address(this).balance,
"Founder Contract: Invalid amount"
);
withdrawAddress.transfer(_amount);
}
| 5,670,588
|
./full_match/42/0xc5AB10c94398a1113ec39a20ba902683b59b1aDc/sources/Withdrawable.sol
|
Withdraw asset. _assetAddress Asset to be withdrawn./
|
function withdraw(address _assetAddress) public onlyOwner {
uint assetBalance;
if (_assetAddress == ETHER) {
assetBalance = self.balance;
assetBalance = ERC20(_assetAddress).balanceOf(address(this));
ERC20(_assetAddress).safeTransfer(msg.sender, assetBalance);
}
emit LogWithdraw(msg.sender, _assetAddress, assetBalance);
}
| 16,210,550
|
./full_match/77/0xcA47f86f29Ab274257792a2Cf24B7299d449cF06/sources/deploy/contracts/synthereum-pool/v5/LiquidityPool.sol
|
Returns the percentage of overcollateralization to which a liquidation can triggered return Percentage of overcollateralization/
|
function collateralRequirement() external view override returns (uint256) {
return liquidationData.collateralRequirement.rawValue;
}
| 5,047,251
|
./full_match/42220/0x9B64E8EaBD1a035b148cE970d3319c5C3Ad53EC3/sources/lib/mento-core-2.2.0/contracts/swap/BiPoolManager.sol
|
Calculate amountIn of tokenIn for a given amountOut of tokenOut exchange The exchange to operate on tokenIn The token to be sold tokenOut The token to be bought scaledAmountOut The amount of tokenOut to be bought scaled to 18 decimals return scaledAmountIn The amount of tokenIn to be sold scaled to 18 decimals return bucketsUpdated Wether the buckets were updated during the quote/
|
function _getAmountIn(
PoolExchange memory exchange,
address tokenIn,
address tokenOut,
uint256 scaledAmountOut
) internal view returns (uint256 scaledAmountIn, bool bucketsUpdated) {
require(
(tokenIn == exchange.asset0 && tokenOut == exchange.asset1) ||
(tokenIn == exchange.asset1 && tokenOut == exchange.asset0),
"tokenIn and tokenOut must match exchange"
);
(exchange, bucketsUpdated) = updateBucketsIfNecessary(exchange);
if (tokenIn == exchange.asset0) {
scaledAmountIn = exchange.pricingModule.getAmountIn(
exchange.bucket0,
exchange.bucket1,
exchange.config.spread.unwrap(),
scaledAmountOut
);
scaledAmountIn = exchange.pricingModule.getAmountIn(
exchange.bucket1,
exchange.bucket0,
exchange.config.spread.unwrap(),
scaledAmountOut
);
}
}
| 16,335,470
|
./partial_match/1/0x069c0Ed12dB7199c1DdAF73b94de75AAe8061d33/sources/src/ARV.sol
|
supply of ARV (minting and burning) is entirely controlled by the tokenLocker contract and therefore the staking mechanism/
|
function mint(address to, uint256 amount) external onlyTokenLocker {
_mint(to, amount);
}
| 15,497,921
|
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "./lib/Withdrawable.sol";
import "./TraceToMetaInfoInterface.sol";
import "./TraceToRequestorListInterface.sol";
import "./TraceToSPListInterface.sol";
import "./TraceToServiceCreditInterface.sol";
/**
* @title TraceToServiceCredit
* @dev This contract is for keeping the service balance, and notify SP to check new profiles
*/
contract TraceToServiceCredit is Withdrawable, TraceToServiceCreditInterface{
using SafeMath for uint256;
struct Credit{
uint256 serviceCount;
uint256 tokenCount;
bool isInit;
}
struct Service{
mapping(address => Credit) credits;
address[] sp;
uint256 spCount;
}
mapping(address => Service) ServiceCredit;
struct Payment{
mapping(address => uint256) tokenCount;
}
struct RequestorPayment{
mapping(address => Payment) pending;
}
mapping(uint256 => RequestorPayment) PendingPayment;
mapping(address => uint256) PendingSPPayment;
mapping(address => uint256) PendingVPayment;
TraceToMetaInfoInterface public tracetoMetaInfo;
IERC20 public token;
/**
* @dev only requestor who have topped up before
*/
modifier onlyRequestor {
require(TraceToRequestorListInterface(tracetoMetaInfo.getRequestorWL()).isRequestorPR(msg.sender) && ServiceCredit[msg.sender].spCount > 0);
_;
}
event Topup(address requestor, address sp, uint256 count);
event Pending(address requestor, address sp, uint256 profile);
event Finished(address requestor, address sp, uint256 profile);
event SPReview(address requestor, address sp, string comments, uint256 reputation);
/**
* @dev constructor of this contract, it will transfer ownership and use the whitelists set in meta info contract
* @param owner Owner of this contract
* @param _metaInfo meta info contract address
*/
constructor(address owner, address _metaInfo)
public {
transferOwnership(owner);
tracetoMetaInfo = TraceToMetaInfoInterface(_metaInfo);
token = IERC20(tracetoMetaInfo.getTokenContract());
}
/**
* @dev topup for one sp, it will withdraw T2T token from your wallet as deposit
* @notice The service count denotes how much services the requestor is eligble for.
* The token count is the amount paid by requestor.
* @param _requestor the requestor PR contract address
* @param _sp the sp address
* @param _count the service count
*/
function topup(address _requestor, address _sp, uint256 _count)
public {
require(TraceToRequestorListInterface(tracetoMetaInfo.getRequestorWL()).isRequestorPR(_requestor) && TraceToSPListInterface(tracetoMetaInfo.getSPWL()).isSP(_sp));
require(token.transferFrom(msg.sender, address(this), _count.mul(TraceToSPListInterface(tracetoMetaInfo.getSPWL()).getSPRate(_sp))));
if(!ServiceCredit[_requestor].credits[_sp].isInit){
ServiceCredit[_requestor].sp.push(_sp);
ServiceCredit[_requestor].spCount = ServiceCredit[_requestor].spCount.add(1);
ServiceCredit[_requestor].credits[_sp].isInit = true;
}
ServiceCredit[_requestor].credits[_sp].serviceCount = ServiceCredit[_requestor].credits[_sp].serviceCount.add(_count);
ServiceCredit[_requestor].credits[_sp].tokenCount = ServiceCredit[_requestor].credits[_sp].tokenCount.add(_count.mul(TraceToSPListInterface(tracetoMetaInfo.getSPWL()).getSPRate(_sp)));
emit Topup(_requestor, _sp, _count);
}
/**
* @dev return the remaining token deposit and service count
* @param _sp the sp address
* @return tokenCount the token deposit in this contract
* @return serviceCount the service count balance
*/
function getBalance(address _sp)
public
view
returns (uint256 tokenCount, uint256 serviceCount){
if(!ServiceCredit[msg.sender].credits[_sp].isInit){
return (0, 0);
}else{
return (ServiceCredit[msg.sender].credits[_sp].tokenCount, ServiceCredit[msg.sender].credits[_sp].serviceCount);
}
}
/**
* @dev set the profile as pending, deduct the balance
* @notice this is the addition of a profile, called by the requestor via the ProfileResutl contract.
* @param _profile the profile id
*/
function addPending(uint256 _profile)
public
onlyRequestor {
for(uint256 idx = 0; idx < ServiceCredit[msg.sender].spCount; idx = idx.add(1)){
address _sp = ServiceCredit[msg.sender].sp[idx];
if(ServiceCredit[msg.sender].credits[_sp].serviceCount > 0){
uint256 _price = ServiceCredit[msg.sender].credits[_sp].tokenCount.div(ServiceCredit[msg.sender].credits[_sp].serviceCount);
ServiceCredit[msg.sender].credits[_sp].tokenCount = ServiceCredit[msg.sender].credits[_sp].tokenCount.sub(_price);
ServiceCredit[msg.sender].credits[_sp].serviceCount = ServiceCredit[msg.sender].credits[_sp].serviceCount.sub(1);
PendingPayment[_profile].pending[msg.sender].tokenCount[_sp] = PendingPayment[_profile].pending[msg.sender].tokenCount[_sp].add(_price);
emit Pending(msg.sender, _sp, _profile);
}
}
}
/**
* @dev Set a review for a SP, can only call by requestor PR contract
* @param _sp the sp address
* @param _comments the comment for this SP
* @param _reputation the reputation between 0-100
*/
function setReview(address _sp, string _comments, uint256 _reputation)
public
onlyRequestor {
require(TraceToSPListInterface(tracetoMetaInfo.getSPWL()).isSP(_sp) && _reputation <= 10 && _reputation > 0);
emit SPReview(msg.sender, _sp, _comments, _reputation);
}
/**
* @dev set the profile as finished for checking, transfer token to sp and verifiers
* The respective percentages are set in meta info contract
* @param _profile the profile id
* @param _sp the sp who provide the result
*/
function setFinished(uint256 _profile, address _sp)
public
onlyRequestor {
if(token.allowance(address(this), _sp) == 0){
require(
token.approve(
_sp,
PendingPayment[_profile]
.pending[msg.sender]
.tokenCount[_sp]
.mul(tracetoMetaInfo.getSPPercentage())
.div(100)
.add(PendingSPPayment[_sp])
)
);
PendingSPPayment[_sp] = 0;
}else{
PendingSPPayment[_sp] = PendingSPPayment[_sp]
.add(PendingPayment[_profile]
.pending[msg.sender]
.tokenCount[_sp]
.mul(tracetoMetaInfo.getSPPercentage())
.div(100)
);
}
address _v = tracetoMetaInfo.getVerifierWL();
if(token.allowance(address(this), _v) == 0){
require(
token.approve(
tracetoMetaInfo.getVerifierWL(),
PendingPayment[_profile]
.pending[msg.sender]
.tokenCount[_sp]
.mul(tracetoMetaInfo.getVerifierPercentage())
.div(100)
.add(PendingVPayment[_v])
)
);
PendingVPayment[_v] = 0;
}
else{
PendingVPayment[_v] = PendingVPayment[_v]
.add(PendingPayment[_profile]
.pending[msg.sender]
.tokenCount[_sp]
.mul(tracetoMetaInfo.getVerifierPercentage())
.div(100)
);
}
PendingPayment[_profile].pending[msg.sender].tokenCount[_sp] = 0;
emit Finished(msg.sender, _sp, _profile);
}
}
|
set the profile as pending, deduct the balance this is the addition of a profile, called by the requestor via the ProfileResutl contract. _profile the profile id/
|
function addPending(uint256 _profile)
public
onlyRequestor {
for(uint256 idx = 0; idx < ServiceCredit[msg.sender].spCount; idx = idx.add(1)){
address _sp = ServiceCredit[msg.sender].sp[idx];
if(ServiceCredit[msg.sender].credits[_sp].serviceCount > 0){
uint256 _price = ServiceCredit[msg.sender].credits[_sp].tokenCount.div(ServiceCredit[msg.sender].credits[_sp].serviceCount);
ServiceCredit[msg.sender].credits[_sp].tokenCount = ServiceCredit[msg.sender].credits[_sp].tokenCount.sub(_price);
ServiceCredit[msg.sender].credits[_sp].serviceCount = ServiceCredit[msg.sender].credits[_sp].serviceCount.sub(1);
PendingPayment[_profile].pending[msg.sender].tokenCount[_sp] = PendingPayment[_profile].pending[msg.sender].tokenCount[_sp].add(_price);
emit Pending(msg.sender, _sp, _profile);
}
}
}
| 12,876,248
|
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "../../v1/Ownable.sol";
import { FiatTokenV2 } from "../FiatTokenV2.sol";
import { FiatTokenProxy } from "../../v1/FiatTokenProxy.sol";
import { V2UpgraderHelper } from "./V2UpgraderHelper.sol";
/**
* @title V2 Upgrader
* @notice Performs BRLC v2 upgrade, and runs a basic sanity test in a single
* atomic transaction, rolling back if any issues are found. This may be
* overkill, but the peace of mind is worth the gas spent. By performing the
* upgrade atomically, it ensures that there is no disruption of service if the
* upgrade is not successful for some unforeseen circumstances.
* @dev Read docs/v2_upgrade.md
*/
contract V2Upgrader is Ownable {
using SafeMath for uint256;
FiatTokenProxy private _proxy;
FiatTokenV2 private _implementation;
address private _newProxyAdmin;
string private _newName;
V2UpgraderHelper private _helper;
/**
* @notice Constructor
* @param proxy FiatTokenProxy contract
* @param implementation FiatTokenV2 implementation contract
* @param newProxyAdmin Grantee of proxy admin role after upgrade
* @param newName New ERC20 name (e.g. "BRL//C" -> "BRL Coin")
*/
constructor(
FiatTokenProxy proxy,
FiatTokenV2 implementation,
address newProxyAdmin,
string memory newName
) public Ownable() {
_proxy = proxy;
_implementation = implementation;
_newProxyAdmin = newProxyAdmin;
_newName = newName;
_helper = new V2UpgraderHelper(address(proxy));
}
/**
* @notice The address of the FiatTokenProxy contract
* @return Contract address
*/
function proxy() external view returns (address) {
return address(_proxy);
}
/**
* @notice The address of the FiatTokenV2 implementation contract
* @return Contract address
*/
function implementation() external view returns (address) {
return address(_implementation);
}
/**
* @notice The address of the V2UpgraderHelper contract
* @return Contract address
*/
function helper() external view returns (address) {
return address(_helper);
}
/**
* @notice The address to which the proxy admin role will be transferred
* after the upgrade is completed
* @return Address
*/
function newProxyAdmin() external view returns (address) {
return _newProxyAdmin;
}
/**
* @notice New ERC20 token name
* @return New Name
*/
function newName() external view returns (string memory) {
return _newName;
}
/**
* @notice Upgrade, transfer proxy admin role to a given address, run a
* sanity test, and tear down the upgrader contract, in a single atomic
* transaction. It rolls back if there is an error.
*/
function upgrade() external onlyOwner {
// The helper needs to be used to read contract state because
// AdminUpgradeabilityProxy does not allow the proxy admin to make
// proxy calls.
// Check that this contract sufficient funds to run the tests
uint256 contractBal = _helper.balanceOf(address(this));
require(contractBal >= 2e5, "V2Upgrader: 0.2 BRLC needed");
uint256 callerBal = _helper.balanceOf(msg.sender);
// Keep original contract metadata
string memory symbol = _helper.symbol();
uint8 decimals = _helper.decimals();
string memory currency = _helper.currency();
address masterMinter = _helper.masterMinter();
address owner = _helper.fiatTokenOwner();
address pauser = _helper.pauser();
address blacklister = _helper.blacklister();
// Change implementation contract address
_proxy.upgradeTo(address(_implementation));
// Transfer proxy admin role
_proxy.changeAdmin(_newProxyAdmin);
// Initialize V2 contract
FiatTokenV2 v2 = FiatTokenV2(address(_proxy));
v2.initializeV2(_newName);
// Sanity test
// Check metadata
require(
keccak256(bytes(_newName)) == keccak256(bytes(v2.name())) &&
keccak256(bytes(symbol)) == keccak256(bytes(v2.symbol())) &&
decimals == v2.decimals() &&
keccak256(bytes(currency)) == keccak256(bytes(v2.currency())) &&
masterMinter == v2.masterMinter() &&
owner == v2.owner() &&
pauser == v2.pauser() &&
blacklister == v2.blacklister(),
"V2Upgrader: metadata test failed"
);
// Test balanceOf
require(
v2.balanceOf(address(this)) == contractBal,
"V2Upgrader: balanceOf test failed"
);
// Test transfer
require(
v2.transfer(msg.sender, 1e5) &&
v2.balanceOf(msg.sender) == callerBal.add(1e5) &&
v2.balanceOf(address(this)) == contractBal.sub(1e5),
"V2Upgrader: transfer test failed"
);
// Test approve/transferFrom
require(
v2.approve(address(_helper), 1e5) &&
v2.allowance(address(this), address(_helper)) == 1e5 &&
_helper.transferFrom(address(this), msg.sender, 1e5) &&
v2.allowance(address(this), msg.sender) == 0 &&
v2.balanceOf(msg.sender) == callerBal.add(2e5) &&
v2.balanceOf(address(this)) == contractBal.sub(2e5),
"V2Upgrader: approve/transferFrom test failed"
);
// Transfer any remaining BRLC to the caller
withdrawBRLC();
// Tear down
_helper.tearDown();
selfdestruct(msg.sender);
}
/**
* @notice Withdraw any BRLC in the contract
*/
function withdrawBRLC() public onlyOwner {
IERC20 brlc = IERC20(address(_proxy));
uint256 balance = brlc.balanceOf(address(this));
if (balance > 0) {
require(
brlc.transfer(msg.sender, balance),
"V2Upgrader: failed to withdraw BRLC"
);
}
}
/**
* @notice Transfer proxy admin role to newProxyAdmin, and self-destruct
*/
function abortUpgrade() external onlyOwner {
// Transfer proxy admin role
_proxy.changeAdmin(_newProxyAdmin);
// Tear down
_helper.tearDown();
selfdestruct(msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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
*
* Copyright (c) 2018 zOS Global Limited.
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @notice The Ownable contract has an owner address, and provides basic
* authorization control functions
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
* Modifications:
* 1. Consolidate OwnableStorage into this contract (7/13/18)
* 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
* 3. Make public functions external (5/27/20)
*/
contract Ownable {
// Owner of the contract
address private _owner;
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev The constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
setOwner(msg.sender);
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @dev Sets a new owner address
*/
function setOwner(address newOwner) internal {
_owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == _owner, "Ownable: caller is not the 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) external onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
setOwner(newOwner);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol";
import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
import { EIP712 } from "../util/EIP712.sol";
import { EIP712Domain } from "./EIP712Domain.sol";
import { EIP3009 } from "./EIP3009.sol";
import { EIP2612 } from "./EIP2612.sol";
/**
* @title FiatToken V2
* @notice ERC20 Token backed by fiat reserves, version 2
*/
contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
uint8 internal _initializedVersion;
/**
* @notice Initialize v2
* @param newName New token name
*/
function initializeV2(string calldata newName) external {
// solhint-disable-next-line reason-string
require(initialized && _initializedVersion == 0);
name = newName;
DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2");
_initializedVersion = 1;
}
/**
* @notice Increase the allowance by a given increment
* @param spender Spender's address
* @param increment Amount of increase in allowance
* @return True if successful
*/
function increaseAllowance(address spender, uint256 increment)
external
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_increaseAllowance(msg.sender, spender, increment);
return true;
}
/**
* @notice Decrease the allowance by a given decrement
* @param spender Spender's address
* @param decrement Amount of decrease in allowance
* @return True if successful
*/
function decreaseAllowance(address spender, uint256 decrement)
external
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_decreaseAllowance(msg.sender, spender, decrement);
return true;
}
/**
* @notice Execute a transfer with a signed authorization
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
_transferWithAuthorization(
from,
to,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Receive a transfer with a signed authorization from the payer
* @dev This has an additional check to ensure that the payee's address
* matches the caller of this function to prevent front-running attacks.
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
_receiveWithAuthorization(
from,
to,
value,
validAfter,
validBefore,
nonce,
v,
r,
s
);
}
/**
* @notice Attempt to cancel an authorization
* @dev Works only if the authorization is not yet used.
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused {
_cancelAuthorization(authorizer, nonce, v, r, s);
}
/**
* @notice Update allowance with a signed permit
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline Expiration time, seconds since the epoch
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) {
_permit(owner, spender, value, deadline, v, r, s);
}
/**
* @notice Internal function to increase the allowance by a given increment
* @param owner Token owner's address
* @param spender Spender's address
* @param increment Amount of increase
*/
function _increaseAllowance(
address owner,
address spender,
uint256 increment
) internal override {
_approve(owner, spender, allowed[owner][spender].add(increment));
}
/**
* @notice Internal function to decrease the allowance by a given decrement
* @param owner Token owner's address
* @param spender Spender's address
* @param decrement Amount of decrease
*/
function _decreaseAllowance(
address owner,
address spender,
uint256 decrement
) internal override {
_approve(
owner,
spender,
allowed[owner][spender].sub(
decrement,
"ERC20: decreased allowance below zero"
)
);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import {
AdminUpgradeabilityProxy
} from "../upgradeability/AdminUpgradeabilityProxy.sol";
/**
* @title FiatTokenProxy
* @dev This contract proxies FiatToken calls and enables FiatToken upgrades
*/
contract FiatTokenProxy is AdminUpgradeabilityProxy {
constructor(address implementationContract)
public
AdminUpgradeabilityProxy(implementationContract)
{}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { FiatTokenV1 } from "../../v1/FiatTokenV1.sol";
import { Ownable } from "../../v1/Ownable.sol";
/**
* @title V2 Upgrader Helper
* @dev Enables V2Upgrader to read some contract state before it renounces the
* proxy admin role. (Proxy admins cannot call delegated methods.) It is also
* used to test approve/transferFrom.
*/
contract V2UpgraderHelper is Ownable {
address private _proxy;
/**
* @notice Constructor
* @param fiatTokenProxy Address of the FiatTokenProxy contract
*/
constructor(address fiatTokenProxy) public Ownable() {
_proxy = fiatTokenProxy;
}
/**
* @notice The address of the FiatTokenProxy contract
* @return Contract address
*/
function proxy() external view returns (address) {
return address(_proxy);
}
/**
* @notice Call name()
* @return name
*/
function name() external view returns (string memory) {
return FiatTokenV1(_proxy).name();
}
/**
* @notice Call symbol()
* @return symbol
*/
function symbol() external view returns (string memory) {
return FiatTokenV1(_proxy).symbol();
}
/**
* @notice Call decimals()
* @return decimals
*/
function decimals() external view returns (uint8) {
return FiatTokenV1(_proxy).decimals();
}
/**
* @notice Call currency()
* @return currency
*/
function currency() external view returns (string memory) {
return FiatTokenV1(_proxy).currency();
}
/**
* @notice Call masterMinter()
* @return masterMinter
*/
function masterMinter() external view returns (address) {
return FiatTokenV1(_proxy).masterMinter();
}
/**
* @notice Call owner()
* @dev Renamed to fiatTokenOwner due to the existence of Ownable.owner()
* @return owner
*/
function fiatTokenOwner() external view returns (address) {
return FiatTokenV1(_proxy).owner();
}
/**
* @notice Call pauser()
* @return pauser
*/
function pauser() external view returns (address) {
return FiatTokenV1(_proxy).pauser();
}
/**
* @notice Call blacklister()
* @return blacklister
*/
function blacklister() external view returns (address) {
return FiatTokenV1(_proxy).blacklister();
}
/**
* @notice Call balanceOf(address)
* @param account Account
* @return balance
*/
function balanceOf(address account) external view returns (uint256) {
return FiatTokenV1(_proxy).balanceOf(account);
}
/**
* @notice Call transferFrom(address,address,uint256)
* @param from Sender
* @param to Recipient
* @param value Amount
* @return result
*/
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
return FiatTokenV1(_proxy).transferFrom(from, to, value);
}
/**
* @notice Tear down the contract (self-destruct)
*/
function tearDown() external onlyOwner {
selfdestruct(msg.sender);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { FiatTokenV1 } from "../v1/FiatTokenV1.sol";
import { Rescuable } from "./Rescuable.sol";
/**
* @title FiatTokenV1_1
* @dev ERC20 Token backed by fiat reserves
*/
contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol";
abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
function _increaseAllowance(
address owner,
address spender,
uint256 increment
) internal virtual;
function _decreaseAllowance(
address owner,
address spender,
uint256 decrement
) internal virtual;
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { ECRecover } from "./ECRecover.sol";
/**
* @title EIP712
* @notice A library that provides EIP712 helper functions
*/
library EIP712 {
/**
* @notice Make EIP712 domain separator
* @param name Contract name
* @param version Contract version
* @return Domain separator
*/
function makeDomainSeparator(string memory name, string memory version)
internal
view
returns (bytes32)
{
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(
// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
address(this)
)
);
}
/**
* @notice Recover signer's address from a EIP712 signature
* @param domainSeparator Domain separator
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @param typeHashAndData Type hash concatenated with data
* @return Signer's address
*/
function recover(
bytes32 domainSeparator,
uint8 v,
bytes32 r,
bytes32 s,
bytes memory typeHashAndData
) internal pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
keccak256(typeHashAndData)
)
);
return ECRecover.recover(digest, v, r, s);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title EIP712 Domain
*/
contract EIP712Domain {
/**
* @dev EIP712 Domain Separator
*/
bytes32 public DOMAIN_SEPARATOR;
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
import { EIP712Domain } from "./EIP712Domain.sol";
import { EIP712 } from "../util/EIP712.sol";
/**
* @title EIP-3009
* @notice Provide internal implementation for gas-abstracted transfers
* @dev Contracts that inherit from this must wrap these with publicly
* accessible functions, optionally adding modifiers where necessary
*/
abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
bytes32
public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
// keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
bytes32
public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
/**
* @dev authorizer address => nonce => bool (true if nonce is used)
*/
mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event AuthorizationCanceled(
address indexed authorizer,
bytes32 indexed nonce
);
/**
* @notice Returns the state of an authorization
* @dev Nonces are randomly generated 32-byte data unique to the
* authorizer's address
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @return True if the nonce is used
*/
function authorizationState(address authorizer, bytes32 nonce)
external
view
returns (bool)
{
return _authorizationStates[authorizer][nonce];
}
/**
* @notice Execute a transfer with a signed authorization
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireValidAuthorization(from, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(from, nonce);
_transfer(from, to, value);
}
/**
* @notice Receive a transfer with a signed authorization from the payer
* @dev This has an additional check to ensure that the payee's address
* matches the caller of this function to prevent front-running attacks.
* @param from Payer's address (Authorizer)
* @param to Payee's address
* @param value Amount to be transferred
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
* @param nonce Unique nonce
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _receiveWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(to == msg.sender, "FiatTokenV2: caller must be the payee");
_requireValidAuthorization(from, nonce, validAfter, validBefore);
bytes memory data = abi.encode(
RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
from,
to,
value,
validAfter,
validBefore,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from,
"FiatTokenV2: invalid signature"
);
_markAuthorizationAsUsed(from, nonce);
_transfer(from, to, value);
}
/**
* @notice Attempt to cancel an authorization
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _cancelAuthorization(
address authorizer,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
) internal {
_requireUnusedAuthorization(authorizer, nonce);
bytes memory data = abi.encode(
CANCEL_AUTHORIZATION_TYPEHASH,
authorizer,
nonce
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer,
"FiatTokenV2: invalid signature"
);
_authorizationStates[authorizer][nonce] = true;
emit AuthorizationCanceled(authorizer, nonce);
}
/**
* @notice Check that an authorization is unused
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
private
view
{
require(
!_authorizationStates[authorizer][nonce],
"FiatTokenV2: authorization is used or canceled"
);
}
/**
* @notice Check that authorization is valid
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
* @param validAfter The time after which this is valid (unix time)
* @param validBefore The time before which this is valid (unix time)
*/
function _requireValidAuthorization(
address authorizer,
bytes32 nonce,
uint256 validAfter,
uint256 validBefore
) private view {
require(
now > validAfter,
"FiatTokenV2: authorization is not yet valid"
);
require(now < validBefore, "FiatTokenV2: authorization is expired");
_requireUnusedAuthorization(authorizer, nonce);
}
/**
* @notice Mark an authorization as used
* @param authorizer Authorizer's address
* @param nonce Nonce of the authorization
*/
function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
private
{
_authorizationStates[authorizer][nonce] = true;
emit AuthorizationUsed(authorizer, nonce);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
import { EIP712Domain } from "./EIP712Domain.sol";
import { EIP712 } from "../util/EIP712.sol";
/**
* @title EIP-2612
* @notice Provide internal implementation for gas-abstracted approvals
*/
abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32
public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) private _permitNonces;
/**
* @notice Nonces for permit
* @param owner Token owner's address (Authorizer)
* @return Next nonce
*/
function nonces(address owner) external view returns (uint256) {
return _permitNonces[owner];
}
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= now, "FiatTokenV2: permit is expired");
bytes memory data = abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_permitNonces[owner]++,
deadline
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"EIP2612: invalid signature"
);
_approve(owner, spender, value);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol";
import { Ownable } from "./Ownable.sol";
import { Pausable } from "./Pausable.sol";
import { Blacklistable } from "./Blacklistable.sol";
/**
* @title FiatToken
* @dev ERC20 Token backed by fiat reserves
*/
contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
string public currency;
address public masterMinter;
bool internal initialized;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowed;
uint256 internal totalSupply_ = 0;
mapping(address => bool) internal minters;
mapping(address => uint256) internal minterAllowed;
event Mint(address indexed minter, address indexed to, uint256 amount);
event Burn(address indexed burner, uint256 amount);
event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
event MinterRemoved(address indexed oldMinter);
event MasterMinterChanged(address indexed newMasterMinter);
function initialize(
string memory tokenName,
string memory tokenSymbol,
string memory tokenCurrency,
uint8 tokenDecimals,
address newMasterMinter,
address newPauser,
address newBlacklister,
address newOwner
) public {
require(!initialized, "FiatToken: contract is already initialized");
require(
newMasterMinter != address(0),
"FiatToken: new masterMinter is the zero address"
);
require(
newPauser != address(0),
"FiatToken: new pauser is the zero address"
);
require(
newBlacklister != address(0),
"FiatToken: new blacklister is the zero address"
);
require(
newOwner != address(0),
"FiatToken: new owner is the zero address"
);
name = tokenName;
symbol = tokenSymbol;
currency = tokenCurrency;
decimals = tokenDecimals;
masterMinter = newMasterMinter;
pauser = newPauser;
blacklister = newBlacklister;
setOwner(newOwner);
initialized = true;
}
/**
* @dev Throws if called by any account other than a minter
*/
modifier onlyMinters() {
require(minters[msg.sender], "FiatToken: caller is not a minter");
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint. Must be less than or equal
* to the minterAllowance of the caller.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount)
external
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
notBlacklisted(_to)
returns (bool)
{
require(_to != address(0), "FiatToken: mint to the zero address");
require(_amount > 0, "FiatToken: mint amount not greater than 0");
uint256 mintingAllowedAmount = minterAllowed[msg.sender];
require(
_amount <= mintingAllowedAmount,
"FiatToken: mint amount exceeds minterAllowance"
);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
emit Mint(msg.sender, _to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Throws if called by any account other than the masterMinter
*/
modifier onlyMasterMinter() {
require(
msg.sender == masterMinter,
"FiatToken: caller is not the masterMinter"
);
_;
}
/**
* @dev Get minter allowance for an account
* @param minter The address of the minter
*/
function minterAllowance(address minter) external view returns (uint256) {
return minterAllowed[minter];
}
/**
* @dev Checks if account is a minter
* @param account The address to check
*/
function isMinter(address account) external view returns (bool) {
return minters[account];
}
/**
* @notice Amount of remaining tokens spender is allowed to transfer on
* behalf of the token owner
* @param owner Token owner's address
* @param spender Spender's address
* @return Allowance amount
*/
function allowance(address owner, address spender)
external
override
view
returns (uint256)
{
return allowed[owner][spender];
}
/**
* @dev Get totalSupply of token
*/
function totalSupply() external override view returns (uint256) {
return totalSupply_;
}
/**
* @dev Get token balance of an account
* @param account address The account
*/
function balanceOf(address account)
external
override
view
returns (uint256)
{
return balances[account];
}
/**
* @notice Set spender's allowance over the caller's tokens to be a given
* value.
* @param spender Spender's address
* @param value Allowance amount
* @return True if successful
*/
function approve(address spender, uint256 value)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(spender)
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Internal function to set allowance
* @param owner Token owner's address
* @param spender Spender's address
* @param value Allowance amount
*/
function _approve(
address owner,
address spender,
uint256 value
) internal override {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @notice Transfer tokens by spending allowance
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transferFrom(
address from,
address to,
uint256 value
)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(from)
notBlacklisted(to)
returns (bool)
{
require(
value <= allowed[from][msg.sender],
"ERC20: transfer amount exceeds allowance"
);
_transfer(from, to, value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
return true;
}
/**
* @notice Transfer tokens from the caller
* @param to Payee's address
* @param value Transfer amount
* @return True if successful
*/
function transfer(address to, uint256 value)
external
override
whenNotPaused
notBlacklisted(msg.sender)
notBlacklisted(to)
returns (bool)
{
_transfer(msg.sender, to, value);
return true;
}
/**
* @notice Internal function to process transfers
* @param from Payer's address
* @param to Payee's address
* @param value Transfer amount
*/
function _transfer(
address from,
address to,
uint256 value
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(
value <= balances[from],
"ERC20: transfer amount exceeds balance"
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Function to add/update a new minter
* @param minter The address of the minter
* @param minterAllowedAmount The minting amount allowed for the minter
* @return True if the operation was successful.
*/
function configureMinter(address minter, uint256 minterAllowedAmount)
external
whenNotPaused
onlyMasterMinter
returns (bool)
{
minters[minter] = true;
minterAllowed[minter] = minterAllowedAmount;
emit MinterConfigured(minter, minterAllowedAmount);
return true;
}
/**
* @dev Function to remove a minter
* @param minter The address of the minter to remove
* @return True if the operation was successful.
*/
function removeMinter(address minter)
external
onlyMasterMinter
returns (bool)
{
minters[minter] = false;
minterAllowed[minter] = 0;
emit MinterRemoved(minter);
return true;
}
/**
* @dev allows a minter to burn some of its own tokens
* Validates that caller is a minter and that sender is not blacklisted
* amount is less than or equal to the minter's account balance
* @param _amount uint256 the amount of tokens to be burned
*/
function burn(uint256 _amount)
external
whenNotPaused
onlyMinters
notBlacklisted(msg.sender)
{
uint256 balance = balances[msg.sender];
require(_amount > 0, "FiatToken: burn amount not greater than 0");
require(balance >= _amount, "FiatToken: burn amount exceeds balance");
totalSupply_ = totalSupply_.sub(_amount);
balances[msg.sender] = balance.sub(_amount);
emit Burn(msg.sender, _amount);
emit Transfer(msg.sender, address(0), _amount);
}
function updateMasterMinter(address _newMasterMinter) external onlyOwner {
require(
_newMasterMinter != address(0),
"FiatToken: new masterMinter is the zero address"
);
masterMinter = _newMasterMinter;
emit MasterMinterChanged(masterMinter);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { Ownable } from "../v1/Ownable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Rescuable is Ownable {
using SafeERC20 for IERC20;
address private _rescuer;
event RescuerChanged(address indexed newRescuer);
/**
* @notice Returns current rescuer
* @return Rescuer's address
*/
function rescuer() external view returns (address) {
return _rescuer;
}
/**
* @notice Revert if called by any account other than the rescuer.
*/
modifier onlyRescuer() {
require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
_;
}
/**
* @notice Rescue ERC20 tokens locked up in this contract.
* @param tokenContract ERC20 token contract address
* @param to Recipient address
* @param amount Amount to withdraw
*/
function rescueERC20(
IERC20 tokenContract,
address to,
uint256 amount
) external onlyRescuer {
tokenContract.safeTransfer(to, amount);
}
/**
* @notice Assign the rescuer role to a given address.
* @param newRescuer New rescuer's address
*/
function updateRescuer(address newRescuer) external onlyOwner {
require(
newRescuer != address(0),
"Rescuable: new rescuer is the zero address"
);
_rescuer = newRescuer;
emit RescuerChanged(newRescuer);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
abstract contract AbstractFiatTokenV1 is IERC20 {
function _approve(
address owner,
address spender,
uint256 value
) internal virtual;
function _transfer(
address from,
address to,
uint256 value
) internal virtual;
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016 Smart Contract Solutions, Inc.
* Copyright (c) 2018-2020 CENTRE SECZ0
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { Ownable } from "./Ownable.sol";
/**
* @notice Base contract which allows children to implement an emergency stop
* mechanism
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
* Modifications:
* 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
* 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
* 3. Removed whenPaused (6/14/2018)
* 4. Switches ownable library to use ZeppelinOS (7/12/18)
* 5. Remove constructor (7/13/18)
* 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
* 7. Make public functions external (5/27/20)
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
event PauserChanged(address indexed newAddress);
address public pauser;
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
/**
* @dev throws if called by any account other than the pauser
*/
modifier onlyPauser() {
require(msg.sender == pauser, "Pausable: caller is not the pauser");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() external onlyPauser {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() external onlyPauser {
paused = false;
emit Unpause();
}
/**
* @dev update the pauser role
*/
function updatePauser(address _newPauser) external onlyOwner {
require(
_newPauser != address(0),
"Pausable: new pauser is the zero address"
);
pauser = _newPauser;
emit PauserChanged(pauser);
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { Ownable } from "./Ownable.sol";
/**
* @title Blacklistable Token
* @dev Allows accounts to be blacklisted by a "blacklister" role
*/
contract Blacklistable is Ownable {
address public blacklister;
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed _account);
event UnBlacklisted(address indexed _account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
require(
msg.sender == blacklister,
"Blacklistable: caller is not the blacklister"
);
_;
}
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(
!blacklisted[_account],
"Blacklistable: account is blacklisted"
);
_;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address to check
*/
function isBlacklisted(address _account) external view returns (bool) {
return blacklisted[_account];
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
*/
function blacklist(address _account) external onlyBlacklister {
blacklisted[_account] = true;
emit Blacklisted(_account);
}
/**
* @dev Removes account from blacklist
* @param _account The address to remove from the blacklist
*/
function unBlacklist(address _account) external onlyBlacklister {
blacklisted[_account] = false;
emit UnBlacklisted(_account);
}
function updateBlacklister(address _newBlacklister) external onlyOwner {
require(
_newBlacklister != address(0),
"Blacklistable: new blacklister is the zero address"
);
blacklister = _newBlacklister;
emit BlacklisterChanged(blacklister);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @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);
}
}
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016-2019 zOS Global Limited
* Copyright (c) 2018-2020 CENTRE SECZ
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @title ECRecover
* @notice A library that provides a safe ECDSA recovery function
*/
library ECRecover {
/**
* @notice Recover signer's address from a signed message
* @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
* Modifications: Accept v, r, and s as separate arguments
* @param digest Keccak-256 hash digest of the signed message
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
* @return Signer address
*/
function recover(
bytes32 digest,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (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("ECRecover: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECRecover: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(digest, v, r, s);
require(signer != address(0), "ECRecover: invalid signature");
return signer;
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018 zOS Global Limited.
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { UpgradeabilityProxy } from "./UpgradeabilityProxy.sol";
/**
* @notice This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol
* Modifications:
* 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
* 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20)
*/
contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32
private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Contract constructor.
* It sets the `msg.sender` as the proxy administrator.
* @param implementationContract address of the initial implementation.
*/
constructor(address implementationContract)
public
UpgradeabilityProxy(implementationContract)
{
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(msg.sender);
}
/**
* @return The address of the proxy admin.
*/
function admin() external view returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external view returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(
newAdmin != address(0),
"Cannot change the admin of a proxy to the zero address"
);
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be
* called, as described in
* https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
// prettier-ignore
// solhint-disable-next-line avoid-low-level-calls
(bool success,) = address(this).call{value: msg.value}(data);
// solhint-disable-next-line reason-string
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override {
require(
msg.sender != _admin(),
"Cannot call fallback function from the proxy admin"
);
super._willFallback();
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018 zOS Global Limited.
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
import { Proxy } from "./Proxy.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
/**
* @notice This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
* @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol
* Modifications:
* 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
* 2. Use Address utility library from the latest OpenZeppelin (5/13/20)
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32
private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Contract constructor.
* @param implementationContract Address of the initial implementation.
*/
constructor(address implementationContract) public {
assert(
IMPLEMENTATION_SLOT ==
keccak256("org.zeppelinos.proxy.implementation")
);
_setImplementation(implementationContract);
}
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"Cannot set a proxy implementation to a non-contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2018 zOS Global Limited.
*
* 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
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity 0.6.12;
/**
* @notice Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
* @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/Proxy.sol
* Modifications:
* 1. Reformat and conform to Solidity 0.6 syntax (5/13/20)
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
|
Function to add/update a new minter minter The address of the minter minterAllowedAmount The minting amount allowed for the minter return True if the operation was successful./
|
function configureMinter(address minter, uint256 minterAllowedAmount)
external
whenNotPaused
onlyMasterMinter
returns (bool)
{
minters[minter] = true;
minterAllowed[minter] = minterAllowedAmount;
emit MinterConfigured(minter, minterAllowedAmount);
return true;
}
| 44,715
|
./full_match/42/0x8673009734dE8B78296248ad6523997A19eEA080/sources/bswap.sol
|
this low-level function should be called from a contract which performs important safety checks
|
function mint(address to) external lock returns (uint256 liquidity) {
uint256 balance0 = IBentoBoxV1(bento).balanceOf(token0, address(this));
uint256 balance1 = IBentoBoxV1(bento).balanceOf(token1, address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
if (_totalSupply == 0) {
address migrator = IBentoSwapFactory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
require(migrator == address(0), "Must not have migrator");
liquidity = BentoSwapMath.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
}
liquidity = BentoSwapMath.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'BentoSwap: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
emit Mint(msg.sender, amount0, amount1);
}
| 16,238,673
|
./full_match/43114/0x481A2bE40120526a04BCc082596B98Ef7A8F56E4/sources/JoeTest.sol
|
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
|
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "JoeLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"JoeLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
| 4,518,768
|
./full_match/106/0x243FfE78D39375A29024EE2470968dE52016e6f4/sources/contracts/balance_checker.sol
|
/ check if token is actually a contract is it a contract and does it implement balanceOf
|
function tokenBalance(address user, address token) public view returns (uint) {
uint256 tokenCode;
if (tokenCode > 0 && token.call(bytes4(0x70a08231), user)) {
return Token(token).balanceOf(user);
return 0;
}
}
Pass 0x0 as a "token" address to get ETH balance.
Possible error throws:
- extremely large arrays for user and or tokens (gas cost too high)
Returns a one-dimensional that's user.length * tokens.length long. The
array is ordered by all of the 0th users token balances, then the 1th
user, and so on.
| 7,099,558
|
pragma solidity ^0.4.24;
/* ----------------------------------------------------------------------------
Client contract.
This contract is generated for each user (user account). All the transactions of a user are executed from this contract.
Only Aion smart contract can interact with the user account and only when the user schedules transactions.
----------------------------------------------------------------------------*/
contract AionClient {
address private AionAddress;
constructor(address addraion) public{
AionAddress = addraion;
}
function execfunct(address to, uint256 value, uint256 gaslimit, bytes data) external returns(bool) {
require(msg.sender == AionAddress);
return to.call.value(value).gas(gaslimit)(data);
}
function () payable public {}
}
// ----------------------------------------------------------------------------
// SafeMat library
// ----------------------------------------------------------------------------
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;
require(c / a == b);
return c;
}
/** @dev Integer division of two numbers, truncating the quotient.*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
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) {
require(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;
require(c >= a);
return c;
}
}
/* ----------------------------------------------------------------------------
Aion Smart contract (by ETH-Pantheon)
----------------------------------------------------------------------------*/
contract Aion {
using SafeMath for uint256;
address public owner;
uint256 public serviceFee;
uint256 public AionID;
uint256 public feeChangeInterval;
mapping(address => address) public clientAccount;
mapping(uint256 => bytes32) public scheduledCalls;
// Log for executed transactions.
event ExecutedCallEvent(address indexed from, uint256 indexed AionID, bool TxStatus, bool TxStatus_cancel, bool reimbStatus);
// Log for scheduled transactions.
event ScheduleCallEvent(uint256 indexed blocknumber, address indexed from, address to, uint256 value, uint256 gaslimit,
uint256 gasprice, uint256 fee, bytes data, uint256 indexed AionID, bool schedType);
// Log for cancelation of a scheduled call (no fee is charged, all funds are moved from client's smart contract to client's address)
event CancellScheduledTxEvent(address indexed from, uint256 Total, bool Status, uint256 indexed AionID);
// Log for changes in the service fee
event feeChanged(uint256 newfee, uint256 oldfee);
constructor () public {
owner = msg.sender;
serviceFee = 500000000000000;
}
// This function allows to change the address of the owner (admin of the contract)
function transferOwnership(address newOwner) public {
require(msg.sender == owner);
withdraw();
owner = newOwner;
}
// This function creates an account (contract) for a client if his address is
// not yet associated to an account
function createAccount() internal {
if(clientAccount[msg.sender]==address(0x0)){
AionClient newContract = new AionClient(address(this));
clientAccount[msg.sender] = address(newContract);
}
}
/* This function schedules transactions: client should provide an amount of Ether equal to value + gaslimit*gasprice + serviceFee
@param blocknumber block or timestamp at which the transaction should be executed.
@param to recipient of the transaction.
@param value Amount of Wei to send with the transaction.
@param gaslimit maximum amount of gas to spend in the transaction.
@param gasprice value to pay per unit of gas.
@param data transaction data.
@param schedType determines if the transaction is scheduled on blocks or timestamp (true->timestamp)
@return uint256 Identification of the transaction
@return address address of the client account created
*/
function ScheduleCall(uint256 blocknumber, address to, uint256 value, uint256 gaslimit, uint256 gasprice, bytes data, bool schedType) public payable returns (uint,address){
require(msg.value == value.add(gaslimit.mul(gasprice)).add(serviceFee));
AionID = AionID + 1;
scheduledCalls[AionID] = keccak256(abi.encodePacked(blocknumber, msg.sender, to, value, gaslimit, gasprice, serviceFee, data, schedType));
createAccount();
clientAccount[msg.sender].transfer(msg.value);
emit ScheduleCallEvent(blocknumber, msg.sender, to, value, gaslimit, gasprice, serviceFee, data, AionID, schedType);
return (AionID,clientAccount[msg.sender]);
}
/* This function executes the transaction at the correct time/block
Aion off-chain system should provide the correct information for executing a transaction.
The information is checked against the hash of the original data provided by the user saved in scheduledCalls.
If the information does not match, the transaction is reverted.
*/
function executeCall(uint256 blocknumber, address from, address to, uint256 value, uint256 gaslimit, uint256 gasprice,
uint256 fee, bytes data, uint256 aionId, bool schedType) external {
require(msg.sender==owner);
if(schedType) require(blocknumber <= block.timestamp);
if(!schedType) require(blocknumber <= block.number);
require(scheduledCalls[aionId]==keccak256(abi.encodePacked(blocknumber, from, to, value, gaslimit, gasprice, fee, data, schedType)));
AionClient instance = AionClient(clientAccount[from]);
require(instance.execfunct(address(this), gasprice*gaslimit+fee, 2100, hex"00"));
bool TxStatus = instance.execfunct(to, value, gasleft().sub(50000), data);
// If the user tx fails return the ether to user
bool TxStatus_cancel;
if(!TxStatus && value>0){TxStatus_cancel = instance.execfunct(from, value, 2100, hex"00");}
delete scheduledCalls[aionId];
bool reimbStatus = from.call.value((gasleft()).mul(gasprice)).gas(2100)();
emit ExecutedCallEvent(from, aionId,TxStatus, TxStatus_cancel, reimbStatus);
}
/* This function allows clients to cancel scheduled transctions. No fee is charged.
Parameters are the same as in ScheduleCall.
@return bool indicating success or failure.
*/
function cancellScheduledTx(uint256 blocknumber, address from, address to, uint256 value, uint256 gaslimit, uint256 gasprice,
uint256 fee, bytes data, uint256 aionId, bool schedType) external returns(bool) {
if(schedType) require(blocknumber >= block.timestamp+(3 minutes) || blocknumber <= block.timestamp-(5 minutes));
if(!schedType) require(blocknumber > block.number+10 || blocknumber <= block.number-20);
require(scheduledCalls[aionId]==keccak256(abi.encodePacked(blocknumber, from, to, value, gaslimit, gasprice, fee, data, schedType)));
require(msg.sender==from);
AionClient instance = AionClient(clientAccount[msg.sender]);
bool Status = instance.execfunct(from, value+gasprice*gaslimit+fee, 3000, hex"00");
require(Status);
emit CancellScheduledTxEvent(from, value+gasprice*gaslimit+fee, Status, aionId);
delete scheduledCalls[aionId];
return true;
}
// This function allows the owner of the contract to retrieve the fees and the gas price
function withdraw() public {
require(msg.sender==owner);
owner.transfer(address(this).balance);
}
// This function updates the service fee.
// To provide security to the clients the fee can only be updated once per day.
// This is to maintain the same price despite the Ether variation.
// Also, the amount of the update (if increased) can only increase 10% each time.
// Furthermore, an event is fired when the fee has been changed to inform the network.
function updatefee(uint256 fee) public{
require(msg.sender==owner);
require(feeChangeInterval<block.timestamp);
uint256 oldfee = serviceFee;
if(fee>serviceFee){
require(((fee.sub(serviceFee)).mul(100)).div(serviceFee)<=10);
serviceFee = fee;
} else{
serviceFee = fee;
}
feeChangeInterval = block.timestamp + (1 days);
emit feeChanged(serviceFee, oldfee);
}
// fallback- receive Ether
function () public payable {
}
}
|
This function updates the service fee. To provide security to the clients the fee can only be updated once per day. This is to maintain the same price despite the Ether variation. Also, the amount of the update (if increased) can only increase 10% each time. Furthermore, an event is fired when the fee has been changed to inform the network.
|
function updatefee(uint256 fee) public{
require(msg.sender==owner);
require(feeChangeInterval<block.timestamp);
uint256 oldfee = serviceFee;
if(fee>serviceFee){
require(((fee.sub(serviceFee)).mul(100)).div(serviceFee)<=10);
serviceFee = fee;
serviceFee = fee;
}
feeChangeInterval = block.timestamp + (1 days);
emit feeChanged(serviceFee, oldfee);
}
| 12,547,899
|
./full_match/5/0xA3FB1Bf2c657A96A6ae2B432BdF274AE94C1bE05/sources/contracts/CrowdFunding.sol
|
checking if everithing is ok
|
function createCampaign(address _owner, string memory _title, string memory _description,
uint256 _target, uint256 _deadline, string memory _image ) public returns (uint256) {
Campaign storage campaign = campaigns[nrOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
nrOfCampaigns++;
return nrOfCampaigns -1;
}
| 1,868,304
|
pragma solidity ^0.4.22;
/*
* ===3D HODL===
* 10% dividend fee on each buy
* 20% dividend fee on each sell
* 0% TRANSFER FEES in future games
*/
/**
* Games Bridge
*/
contract AcceptsToken3D {
Token3D public tokenContract;
function AcceptsToken3D(address _tokenContract) public {
tokenContract = Token3D(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract Token3D {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "3D HODL";
string public symbol = "3D";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10; // 10% dividend fee on each buy
uint8 constant internal selldividendFee_ = 20; // 10% dividend fee on each sell
uint8 constant internal xFee_ = 0;
uint256 constant internal tokenPriceInitial_ = 0.000000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.0000000001 ether;
uint256 constant internal magnitude = 2**64;
address constant public giveEthxAddress = 0x0000000000000000000000000000000000000000;
uint256 public totalEthxRecieved;
uint256 public totalEthxCollected;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 1000e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.01 ether;
uint256 constant internal ambassadorQuota_ = 0.01 ether; // If ambassor quota not met, disable to open to public.
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
bool public onlyAmbassadors = false;
mapping(address => bool) public canAcceptTokens_;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
function Token3D()
public
{
// add administrators here
administrators[0xded61af41df552e4755c9e97e477643c833904e3] = true;
// add the ambassadors here.
ambassadors_[0xded61af41df552e4755c9e97e477643c833904e3] = true;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseInternal(msg.value, _referredBy);
}
function()
payable
public
{
purchaseInternal(msg.value, 0x0);
}
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, selldividendFee_), 100);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_ethereum, xFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _xPayout);
totalEthxCollected = SafeMath.add(totalEthxCollected, _xPayout);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true);
require(transfer(_to, _value));
if (isContract(_to)) {
AcceptsToken3D receiver = AcceptsToken3D(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, selldividendFee_), 100);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_ethereum, xFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _xPayout);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_ethereum, xFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _xPayout);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, xFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _xPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, selldividendFee_), 100);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_ethereum, xFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _xPayout);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
// Make sure we will send back excess if user sends more then 4 ether before 100 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 4 ether) { // check if the transaction is over 4 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 4 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _xPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, xFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _xPayout);
totalEthxCollected = SafeMath.add(totalEthxCollected, _xPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
wealth redistribution no ref purchase add the referral bonus back to the global dividends cake
|
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
| 1,588,839
|
./full_match/1/0xE3D40116d08FA731253F55C3A51847318A2ddB95/sources/contracts/Staking.sol
|
Extend a stake for an account index uint256 account address amount uint256/ If selected stake is fully vested create a new stake Calculate a new timestamp proportional to the new amount New timestamp limited to current timestamp (amount / newInitial approaches 1)
|
function extendFor(
uint256 index,
address account,
uint256 amount
) public {
require(amount > 0, "AMOUNT_INVALID");
Stake storage selected = allStakes[msg.sender][index];
if (vested(account, index) == selected.initial) {
stakeFor(account, amount);
uint256 newInitial = selected.initial.add(amount);
uint256 newBalance = selected.balance.add(amount);
uint256 newTimestamp =
selected.timestamp +
amount.mul(block.timestamp.sub(selected.timestamp)).div(newInitial);
allStakes[msg.sender][index] = Stake(
duration,
cliff,
newInitial,
newBalance,
newTimestamp
);
token.safeTransferFrom(account, address(this), amount);
emit Transfer(address(0), account, amount);
}
}
| 4,857,862
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
import "./PaiSwapERC20.sol";
import "./libraries/Math.sol";
import "./libraries/UQ112x112.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IPaiSwapFactory.sol";
import "./interfaces/IPaiSwapCallee.sol";
import "./interfaces/IPaiSwapPair.sol";
import "./PaiSwapSlippageToken.sol";
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
contract PaiSwapPair is PaiSwapERC20 {
using SafeMath for uint256;
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
uint256 public constant DECAY_PERIOD = 5 minutes;
uint256 public constant UQ112 = 2**112;
address public factory;
address public token0;
address public token1;
PaiSwapSlippageToken public stoken;
uint224 private virtualPrice; // token0 virtual price, uses single storage slot
uint32 private lastPriceTime; // the latest exchange time
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, "PaiSwap: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function getVirtualPrice() public view returns (uint224 _virtualPrice, uint32 _lastPriceTime) {
_virtualPrice = virtualPrice;
_lastPriceTime = lastPriceTime;
}
function _safeTransfer(address token, address to, uint256 value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "PaiSwap: TRANSFER_FAILED");
}
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, "PaiSwap: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
stoken = new PaiSwapSlippageToken(0);
}
// update reserves and, on the first call per block, price accumulators
function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), "PaiSwap: OVERFLOW");
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IPaiSwapFactory(factory).feeTo();
feeOn = feeTo != address(0);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
address migrator = IPaiSwapFactory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != uint256(-1), "PaiSwap: Bad desired liquidity");
} else {
require(migrator == address(0), "PaiSwap: Must not have migrator");
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, "PaiSwap: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
bool feeOn = _mintFee(_reserve0, _reserve1);
{
uint256 liquidity = balanceOf[address(this)];
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, "PaiSwap: INSUFFICIENT_LIQUIDITY_BURNED");
_burn(address(this), liquidity);
}
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
function _updateVirtualPrice(uint112 _reserve0, uint112 _reserve1) internal {
(uint256 _virtualPrice, uint32 _lastPriceTime) = getVirtualPrice();
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
if (_lastPriceTime < blockTimestamp) {
uint256 currentPrice = uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0));
uint256 timePassed = Math.min(DECAY_PERIOD, block.timestamp.sub(_lastPriceTime));
uint256 timeRemain = DECAY_PERIOD.sub(timePassed);
uint256 price = _virtualPrice.mul(timeRemain).add(currentPrice.mul(timePassed)) / (DECAY_PERIOD);
virtualPrice = uint224(price);
lastPriceTime = blockTimestamp;
}
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, "PaiSwap: INSUFFICIENT_OUTPUT_AMOUNT");
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, "PaiSwap: INSUFFICIENT_LIQUIDITY");
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "PaiSwap: INVALID_TO");
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IPaiSwapCallee(to).PaiSwapCall(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, "PaiSwap: INSUFFICIENT_INPUT_AMOUNT");
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(
balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2),
"PaiSwap: K"
);
}
_updateVirtualPrice(_reserve0, _reserve1);
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
function _getToken0MarketPrice() internal view returns (uint256 price) {
(uint256 _virtualPrice, uint32 _lastPriceTime) = getVirtualPrice();
(uint112 _reserve0, uint112 _reserve1, ) = getReserves();
uint256 currentPrice = uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0));
uint256 timePassed = Math.min(DECAY_PERIOD, block.timestamp.sub(_lastPriceTime));
uint256 timeRemain = DECAY_PERIOD.sub(timePassed);
price = _virtualPrice.mul(timeRemain).add(currentPrice.mul(timePassed)) / (DECAY_PERIOD);
}
function getTokenMarketPrice(address token) external view returns (uint256 price) {
uint256 t0Price = _getToken0MarketPrice();
token == token0 ? price = t0Price : price = UQ112.mul(UQ112) / t0Price;
}
function _getAmountOut(address token, uint256 amountIn, uint256 t0Price) internal view returns (uint256 _out) {
uint256 amountInWithFee = amountIn.mul(997);
if (token == token0) {
uint256 numerator = amountInWithFee.mul(t0Price);
uint256 denominator = UQ112.mul(1000);
_out = numerator / denominator;
} else {
uint256 numerator = amountInWithFee.mul(UQ112);
uint256 denominator = t0Price.mul(1000);
_out = numerator / denominator;
}
}
function _getAmountIn(address token, uint256 amountOut, uint256 t0Price) internal view returns (uint256 _in) {
if (token == token0) {
uint256 numerator = amountOut.mul(1000).mul(t0Price);
uint256 denominator = UQ112.mul(997);
_in = numerator / denominator;
} else {
uint256 numerator = amountOut.mul(1000).mul(UQ112);
uint256 denominator = t0Price.mul(997);
_in = numerator / denominator;
}
}
function getAmountOutMarket(address token, uint256 amountIn) public view returns (uint256 _out, uint256 t0Price) {
t0Price = _getToken0MarketPrice();
_out = _getAmountOut(token, amountIn, t0Price);
}
function getAmountInMarket(address token, uint256 amountOut) public view returns (uint256 _in, uint256 t0Price) {
t0Price = _getToken0MarketPrice();
_in = _getAmountIn(token, amountOut, t0Price);
}
function getAmountOutPool(address token, uint256 amountIn) public view returns (uint256 _out, uint256 t0Price) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves();
t0Price = uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0));
_out = _getAmountOut(token, amountIn, t0Price);
}
function getAmountInPool(address token, uint256 amountOut) public view returns (uint256 _in, uint256 t0Price) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves();
t0Price = uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0));
_in = _getAmountIn(token, amountOut, t0Price);
}
function getAmountOutReal(uint256 amountIn, uint256 _reserveIn, uint256 _reserveOut) internal pure returns (uint256 _out) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(_reserveOut);
uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee);
_out = numerator / denominator;
}
function getAmountInReal(uint256 amountOut, uint256 _reserveIn, uint256 _reserveOut) internal pure returns (uint256 _in) {
uint256 numerator = _reserveIn.mul(amountOut).mul(1000);
uint256 denominator = _reserveOut.sub(amountOut).mul(997);
_in = (numerator / denominator).add(1);
}
function getAmountOutFinal(address token, uint256 amountIn) external view returns (uint256 amountOut, uint256 stokenAmount) {
address _token0 = token0;
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
(uint256 _reserveIn, uint256 _reserveOut) = token == _token0 ? (_reserve0, _reserve1) : (_reserve1, _reserve0);
uint256 amountOutReal = getAmountOutReal(amountIn, _reserveIn, _reserveOut);
(uint256 amountOutMarket, ) = getAmountOutMarket(token, amountIn);
amountOut = amountOutReal;
// arbitrager
if (amountOutReal > amountOutMarket) {
uint256 slippage = amountOutReal.sub(amountOutMarket);
uint256 halfSlippage = slippage / 2;
amountOut = amountOutReal.sub(halfSlippage);
}
(uint256 amountOutPool, uint256 t0Price) = getAmountOutPool(token, amountIn);
uint256 slippage = amountOutPool.sub(amountOutReal);
stokenAmount = token == _token0 ? slippage : slippage.mul(t0Price) / UQ112;
}
function getAmountInFinal(address token, uint256 amountOut) external view returns (uint256 amountIn, uint256 stokenAmount) {
address _token0 = token0;
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
(uint256 _reserveIn, uint256 _reserveOut) = token == _token0 ? (_reserve1, _reserve0) : (_reserve0, _reserve1);
uint256 amountInReal = getAmountInReal(amountOut, _reserveIn, _reserveOut);
(uint256 amountInMarket, ) = getAmountInMarket(token, amountOut);
amountIn = amountInReal;
// arbitrager
if (amountInReal < amountInMarket) {
uint256 slippage = amountInMarket.sub(amountInReal);
uint256 extra = slippage / 2;
amountIn = amountInReal.add(extra);
}
(uint256 amountInPool, uint256 t0Price) = getAmountInPool(token, amountOut);
uint256 slippage = amountInReal.sub(amountInPool);
stokenAmount = token == _token0 ? slippage : slippage.mul(t0Price) / UQ112;
}
function dealSlippageWithIn(address[] calldata path, uint256 amountIn, address to, bool ifmint) external lock returns (uint256 amountOut) {
require(path.length == 2, "PaiSwap: INVALID_PATH");
address _token0 = token0;
uint256 amountOutReal;
uint256 amountOutMarket;
// avoids stack too deep errors
{
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
(uint256 _reserveIn, uint256 _reserveOut) = path[0] == _token0
? (_reserve0, _reserve1)
: (_reserve1, _reserve0);
amountOutReal = getAmountOutReal(amountIn, _reserveIn, _reserveOut);
amountOut = amountOutReal;
(amountOutMarket, ) = getAmountOutMarket(path[0], amountIn);
uint256 balance = IERC20(path[0]).balanceOf(address(this));
uint256 amount = balance.sub(_reserveIn);
require(amount >= amountIn, "PaiSwap: Invalid Amount");
}
// arbitrager
if (amountOutReal > amountOutMarket) {
uint256 slippageExtra = amountOutReal.sub(amountOutMarket);
uint256 halfSlippage = slippageExtra / 2;
amountOut = amountOutReal.sub(halfSlippage);
}
if (ifmint == true) {
(uint256 amountOutPool, uint256 t0Price) = getAmountOutPool(path[0], amountIn);
uint256 slippage = amountOutPool.sub(amountOutReal);
uint256 mintAmount = path[1] == _token0 ? slippage.mul(t0Price) / UQ112 : slippage;
stoken.mint(to, mintAmount);
}
}
function dealSlippageWithOut(address[] calldata path, uint256 amountOut, address to, bool ifmint) external lock returns (uint256 extra) {
require(path.length == 2, "PaiSwap: INVALID_PATH");
address _token0 = token0;
uint256 amountInReal;
uint256 amountInMarket;
// avoids stack too deep errors
{
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
(uint256 _reserveIn, uint256 _reserveOut) = path[0] == _token0
? (_reserve0, _reserve1)
: (_reserve1, _reserve0);
amountInReal = getAmountInReal(amountOut, _reserveIn, _reserveOut);
(amountInMarket, ) = getAmountInMarket(path[1], amountOut);
}
// arbitrager
if (amountInReal < amountInMarket) {
uint256 slippageExtra = amountInMarket.sub(amountInReal);
extra = slippageExtra / 2;
}
if (ifmint == true) {
(uint256 amountInPool, uint256 t0Price) = getAmountInPool(path[1], amountOut);
uint256 slippage = amountInReal.sub(amountInPool);
uint256 mintAmount = path[0] == _token0 ? slippage.mul(t0Price) / UQ112 : slippage;
stoken.mint(to, mintAmount);
}
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
|
avoids stack too deep errors arbitrager
|
function dealSlippageWithIn(address[] calldata path, uint256 amountIn, address to, bool ifmint) external lock returns (uint256 amountOut) {
require(path.length == 2, "PaiSwap: INVALID_PATH");
address _token0 = token0;
uint256 amountOutReal;
uint256 amountOutMarket;
{
(uint256 _reserveIn, uint256 _reserveOut) = path[0] == _token0
? (_reserve0, _reserve1)
: (_reserve1, _reserve0);
amountOutReal = getAmountOutReal(amountIn, _reserveIn, _reserveOut);
amountOut = amountOutReal;
(amountOutMarket, ) = getAmountOutMarket(path[0], amountIn);
uint256 balance = IERC20(path[0]).balanceOf(address(this));
uint256 amount = balance.sub(_reserveIn);
require(amount >= amountIn, "PaiSwap: Invalid Amount");
}
if (amountOutReal > amountOutMarket) {
uint256 slippageExtra = amountOutReal.sub(amountOutMarket);
uint256 halfSlippage = slippageExtra / 2;
amountOut = amountOutReal.sub(halfSlippage);
}
if (ifmint == true) {
(uint256 amountOutPool, uint256 t0Price) = getAmountOutPool(path[0], amountIn);
uint256 slippage = amountOutPool.sub(amountOutReal);
uint256 mintAmount = path[1] == _token0 ? slippage.mul(t0Price) / UQ112 : slippage;
stoken.mint(to, mintAmount);
}
}
| 2,502,079
|
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "./assign.sol";
contract demo is assign{
mapping(uint => uint) backrecord;
/**************用户定义空间***************/
/**************创建评估单功能类***************/
/**
* guobin
* 创建评估单基本信息
*/
function addvaluation(
string memory Frame_number, //车架号
string memory Number_plate, //号码车牌
string memory Vehicle_type, //车辆类型
string memory Brand_number, //品牌型号
string memory car_displacement, //汽车排量(L)
string memory approval_passengers, //核定载客量
string memory Engine_number, //发动机号码
string memory Manufacture_date, //出厂日期
uint Evaluation, //评估价值
string memory Timestammp, //时间戳
uint evaluation_index //评估单编号(由js保证唯一性,前端代码放入ipfs,保证不可篡改性)
) public {
_addvaluation(Frame_number,Number_plate,Vehicle_type,Brand_number,car_displacement,approval_passengers,Engine_number,Manufacture_date,Evaluation,Timestammp,evaluation_index); //添加评估单信息
}
/**
* guobin
* 添加评估单图片并进行分配
*/
function addphoto(
string memory photo1,
string memory photo2,
string memory photo3,
string memory photo4,
string memory photo5,
string memory photo6,
string memory photo7,
string memory photo8,
uint evaluation_index
) public payable {
_addphoto(photo1,photo2,photo3,photo4,photo5,photo6,photo7,photo8,evaluation_index);
distribution(evaluation_index,statistic(0)); //对该评估单进行评估师分配
}
/**
* guobin
* 返回原始评估单编号
*/
function backordernumber() view public returns (uint) {
return _backordernumber();
}
/**
* guobin
* 评估师对订单进行退回
*/
function backwork(uint evaluation_index) public {
if(checkbackstate(evaluation_index) == 1) {
finishwork(evaluation_index,1);
}
else {
finishwork(evaluation_index,0);
distribution(evaluation_index,statistic(1)); //对该评估单重新分配评估师
backrecord[evaluation_index] += 1;
_getcreator(evaluation_index).transfer(100);
}
}
/**
* guobin
* 检查该评估单退回次数
*/
function checkbackstate(uint evaluation_index) internal view returns (uint) {
return backrecord[evaluation_index];
}
/**
* guobin
* 评估师对订单进行评估
*/
function evaluate(uint index,uint value) public {
_evaluate(index,value);
}
/**
* guobin
* 返回当前用户的所有评估单编号
*/
function backvaluation() view public returns (uint[]) {
return _backvaluation();
}
/**
* guobin
* 存储指定评估单评估状态
*/
function setstate(uint index,string condition) public {
_setstate(index,condition);
}
/**
* guobin
* 获取指定评估单价格
*/
function displayvalue(uint index) view public returns (uint) {
return _displayvalue(index);
}
/**
* guobin
* 获取指定评估单评估信息
*/
function displayinfo(uint index,uint num) view public returns (string) {
return _displayinfo(index,num);
}
/**
* guobin
* 获取指定评估单的创建用户
*/
function getcreator(uint index) view public returns(address) {
return _getcreator(index);
}
/**
* guobin
* 获取指定评估单的评估师
*/
function getassessor(uint index) view public returns(address) {
return _getassessor(index);
}
/**************通证买卖功能类***************/
/**
* guobin
* 购买通证
*/
function buy(uint amount) public payable {
_buy(amount);
}
/**
* guobin
* 卖出通证
*/
function sell(uint256 amount,uint256 eth_amount) public payable {
_sell(amount,eth_amount);
}
/**
* guobin
* 显示平台资金池中以太币资金量
*/
function displaybalance() view public returns (uint256) {
return _displaybalance();
}
/**
* guobin
* 显示当前用户持有以太币数量
*/
function displayethbalance() view public returns (uint256) {
return _displayethbalance();
}
/**
* guobin
* 显示当前用户通证数量
*/
function displayaccount() view public returns (uint256) {
return _displayaccount();
}
/**
* guobin
* 计算当前用户,订单退回情况下的竞争力
*/
function displayaccountforarbitrage(address send) public view returns (uint) {
return calc(send,1);
}
/**
* guobin
* 显示已发行的通证总数
*/
function displaytoken() view public returns (uint256) {
return _displaytoken();
}
/**
* guobin
* 显示当前用户的交易次数
*/
function distranumber() view public returns (uint256) {
return _distranumber();
}
/**
* guobin
* 显示指定用户申诉数量
*/
function displaycreate() view public returns (uint) {
return _displaycreate();
}
/**
* guobin
* 显示指定评估师申诉数量
*/
function displaywork() view public returns (uint) {
return _displaywork();
}
/**************评估师定义空间***************/
/**
* guobin
* 注册评估师
*/
function registertest(uint amount,uint scale,string logintime) public payable {
_registertest(logintime);
_buy(amount);
_Enter_quote(scale);
}
/**
* guobin
* 设置评估师报价
*/
function Enter_quote(uint value) public {
_Enter_quote(value);
}
/**
* guobin
* 返回评估师报价
*/
function check_quote() public view returns (uint) {
return _check_quote(msg.sender);
}
/**
* guobin
* 返回当前评估师注册时间
*/
function checktime() view public returns (string) {
return _checktime();
}
/**
* guobin
* 检查用户状态(是否为评估师,是:1,否:0)
*/
function checkuser() view public returns (uint) {
return _checkuser();
}
/**
* guobin
* 注销评估师
*/
function unregister() public {
_unregister();
}
/**
* guobin
* 返回所有评估师地址
*/
function backofwork() view public returns (address[]) {
return _backofwork();
}
/**
* guobin
* 返回当前评估师的所有评估单编号
*/
function backvalnumber() view public returns (uint[]) {
return _backvalnumber();
}
/**************仲裁定义空间***************/
/**
* guobin
* 返回当前仲裁者的所有评估单编号
*/
function backappnumber() view public returns (uint[]) {
return _backappnumber();
}
/**
* guobin
* 将申诉订单编号分配给仲裁者
*/
function appealdistribution(uint number,address appeal1,address appeal2,address appeal3,address appeal4,address appeal5) public {
_appealdistribution(number,appeal1,appeal2,appeal3,appeal4,appeal5);
_setappeal(_getcreator(number),_getassessor(number));
}
/**
* guobin
* 当前仲裁者对本订单是否具备仲裁条件
*/
function appealesituation(uint index) public view returns (uint) {
_appealesituation(index);
}
/**
* guobin
* 仲裁者对订单进行评估
*/
function appealevaluate(uint index,uint value) public {
_appealevaluate(index,value);
}
/**
* guobin
* 仲裁订单进度查询
*/
function appealeschedule(uint index) public view returns (uint) {
return _appealeschedule(index);
}
/**
* guobin
* 返回排行榜中所有评估单编号
*/
function backLeaderboard() public view returns (uint[]) {
return _backLeaderboard();
}
/**
* guobin
* 返回排行榜中评估单长度
*/
function backLength() public view returns (uint) {
return _backLength();
}
}
|
guobin 检查该评估单退回次数/
|
function checkbackstate(uint evaluation_index) internal view returns (uint) {
return backrecord[evaluation_index];
}
| 895,574
|
pragma solidity 0.4.25;
/**
* @title SafeCompare
*/
library SafeCompare {
function stringCompare(string str1, string str2) internal pure returns(bool) {
return keccak256(abi.encodePacked(str1)) == keccak256(abi.encodePacked(str2));
}
}
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;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract UsdtERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns(uint256);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage _role, address _addr)
internal {
_role.bearer[_addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage _role, address _addr)
internal {
_role.bearer[_addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage _role, address _addr)
internal
view {
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns(bool) {
return _role.bearer[_addr];
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether there is code in the target address
* @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 address to check
* @return whether there is code in the target address
*/
function isContract(address addr) internal view returns(bool) {
uint256 size;
assembly {
size: = extcodesize(addr)
}
return size > 0;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev 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;
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
*/
contract RBAC {
using Roles
for Roles.Role;
mapping(string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view {
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns(bool) {
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal {
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal {
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role) {
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract PartnerAuthority is Ownable {
address public partner;
/**
* Event for setPartner logging
* @param oldPartner the old Partner
* @param newPartner the new Partner
*/
event SetPartner(address oldPartner, address newPartner);
/**
* @dev Throws if called by any account other than the owner or the Partner.
*/
modifier onlyOwnerOrPartner() {
require(msg.sender == owner || msg.sender == partner);
_;
}
/**
* @dev Throws if called by any account other than the Partner.
*/
modifier onlyPartner() {
require(msg.sender == partner);
_;
}
/**
* @dev setPartner, set the partner address.
*/
function setPartner(address _partner) public onlyOwner {
require(_partner != address(0));
emit SetPartner(partner, _partner);
partner = _partner;
}
/**
* @dev removePartner, remove partner address.
*/
function removePartner() public onlyOwner {
delete partner;
}
}
contract RBACOperator is Ownable, RBAC {
/**
* A constant role name for indicating operator.
*/
string public constant ROLE_OPERATOR = "operator";
address public partner;
/**
* Event for setPartner logging
* @param oldPartner the old Partner
* @param newPartner the new Partner
*/
event SetPartner(address oldPartner, address newPartner);
/**
* @dev Throws if called by any account other than the owner or the Partner.
*/
modifier onlyOwnerOrPartner() {
require(msg.sender == owner || msg.sender == partner);
_;
}
/**
* @dev Throws if called by any account other than the Partner.
*/
modifier onlyPartner() {
require(msg.sender == partner);
_;
}
/**
* @dev setPartner, set the partner address.
* @param _partner the new partner address.
*/
function setPartner(address _partner) public onlyOwner {
require(_partner != address(0));
emit SetPartner(partner, _partner);
partner = _partner;
}
/**
* @dev removePartner, remove partner address.
*/
function removePartner() public onlyOwner {
delete partner;
}
/**
* @dev the modifier to operate
*/
modifier hasOperationPermission() {
checkRole(msg.sender, ROLE_OPERATOR);
_;
}
/**
* @dev add a operator role to an address
* @param _operator address
*/
function addOperater(address _operator) public onlyOwnerOrPartner {
addRole(_operator, ROLE_OPERATOR);
}
/**
* @dev remove a operator role from an address
* @param _operator address
*/
function removeOperater(address _operator) public onlyOwnerOrPartner {
removeRole(_operator, ROLE_OPERATOR);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns(uint256);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function approve(address spender, uint256 value) public returns(bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract UsdtERC20 is UsdtERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title pledge pool base
* @dev a base tokenPool, any tokenPool for a specific token should inherit from this tokenPool.
*/
contract PledgePoolBase is RBACOperator {
using SafeMath for uint256;
using AddressUtils for address;
// Record pledge details.
mapping(uint256 => Escrow) internal escrows;
/**
* @dev Information structure of pledge.
*/
struct Escrow {
uint256 pledgeSum;
address payerAddress;
string tokenName;
}
// -----------------------------------------
// TokenPool external interface
// -----------------------------------------
/**
* @dev addRecord, interface to add record.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function addRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) public hasOperationPermission returns(bool) {
_preValidateAddRecord(_payerAddress, _pledgeSum, _pledgeId, _tokenName);
_processAddRecord(_payerAddress, _pledgeSum, _pledgeId, _tokenName);
return true;
}
/**
* @dev withdrawToken, withdraw pledge token.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function withdrawToken(uint256 _pledgeId, address _maker, uint256 _num) public hasOperationPermission returns(bool) {
_preValidateWithdraw(_maker, _num, _pledgeId);
_processWithdraw(_maker, _num, _pledgeId);
return true;
}
/**
* @dev refundTokens, interface to refund
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function refundTokens(uint256 _pledgeId, uint256 _returnSum, address _targetAddress) public hasOperationPermission returns(bool) {
_preValidateRefund(_returnSum, _targetAddress, _pledgeId);
_processRefund(_returnSum, _targetAddress, _pledgeId);
return true;
}
/**
* @dev getLedger, Query the pledge details of the pledge number in the pool.
* @param _pledgeId pledge contract index number.
*/
function getLedger(uint256 _pledgeId) public view returns(uint256 num, address payerAddress, string tokenName) {
require(_pledgeId > 0);
num = escrows[_pledgeId].pledgeSum;
payerAddress = escrows[_pledgeId].payerAddress;
tokenName = escrows[_pledgeId].tokenName;
}
// -----------------------------------------
// TokenPool internal interface (extensible)
// -----------------------------------------
/**
* @dev _preValidateAddRecord, Validation of an incoming AddRecord. Use require statemens to revert state when conditions are not met.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function _preValidateAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) view internal {
require(_pledgeSum > 0 && _pledgeId > 0
&& _payerAddress != address(0)
&& bytes(_tokenName).length > 0
&& address(msg.sender).isContract()
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processAddRecord, Executed when a AddRecord has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _payerAddress Address performing the pleadge.
* @param _pledgeSum the value to pleadge.
* @param _pledgeId pledge contract index number.
* @param _tokenName pledge token name.
*/
function _processAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) internal {
Escrow memory escrow = Escrow(_pledgeSum, _payerAddress, _tokenName);
escrows[_pledgeId] = escrow;
}
/**
* @dev _preValidateRefund, Validation of an incoming refund. Use require statemens to revert state when conditions are not met.
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function _preValidateRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) view internal {
require(_returnSum > 0 && _pledgeId > 0
&& _targetAddress != address(0)
&& address(msg.sender).isContract()
&& _returnSum <= escrows[_pledgeId].pledgeSum
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processRefund, Executed when a Refund has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _pledgeId pledge contract index number.
* @param _targetAddress transfer target address.
* @param _returnSum return token sum.
*/
function _processRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) internal {
escrows[_pledgeId].pledgeSum = escrows[_pledgeId].pledgeSum.sub(_returnSum);
}
/**
* @dev _preValidateWithdraw, Withdraw initiated parameter validation.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function _preValidateWithdraw(address _maker, uint256 _num, uint256 _pledgeId) view internal {
require(_num > 0 && _pledgeId > 0
&& _maker != address(0)
&& address(msg.sender).isContract()
&& _num <= escrows[_pledgeId].pledgeSum
&& PledgeContract(msg.sender).getPledgeId()==_pledgeId
);
}
/**
* @dev _processWithdraw, Withdraw data update.
* @param _pledgeId pledge contract index number.
* @param _maker borrower address.
* @param _num withdraw token sum.
*/
function _processWithdraw(address _maker, uint256 _num, uint256 _pledgeId) internal {
escrows[_pledgeId].pledgeSum = escrows[_pledgeId].pledgeSum.sub(_num);
}
}
/**
* @title OrderManageContract
* @dev Order process management contract.
*/
contract OrderManageContract is PartnerAuthority {
using SafeMath for uint256;
using SafeCompare for string;
/**
* @dev Status of current business execution contract.
*/
enum StatusChoices {
NO_LOAN,
REPAYMENT_WAITING,
REPAYMENT_ALL,
CLOSE_POSITION,
OVERDUE_STOP
}
string internal constant TOKEN_ETH = "ETH";
string internal constant TOKEN_USDT = "USDT";
address public maker;
address public taker;
address internal token20;
uint256 public toTime;
// the amount of the borrower’s final loan.
uint256 public outLoanSum;
uint256 public repaymentSum;
uint256 public lastRepaymentSum;
string public loanTokenName;
// Borrower's record of the pledge.
StatusChoices internal status;
// Record the amount of the borrower's offline transfer.
mapping(address => uint256) public ethAmount;
/**
* Event for takerOrder logging.
* @param taker address of investor.
* @param outLoanSum the amount of the borrower’s final loan.
*/
event TakerOrder(address indexed taker, uint256 outLoanSum);
/**
* Event for executeOrder logging.
* @param maker address of borrower.
* @param lastRepaymentSum current order repayment amount.
*/
event ExecuteOrder(address indexed maker, uint256 lastRepaymentSum);
/**
* Event for forceCloseOrder logging.
* @param toTime order repayment due date.
* @param transferSum balance under current contract.
*/
event ForceCloseOrder(uint256 indexed toTime, uint256 transferSum);
/**
* Event for WithdrawToken logging.
* @param taker address of investor.
* @param refundSum number of tokens withdrawn.
*/
event WithdrawToken(address indexed taker, uint256 refundSum);
function() external payable {
// Record basic information about the borrower's REPAYMENT ETH
ethAmount[msg.sender] = ethAmount[msg.sender].add(msg.value);
}
/**
* @dev Constructor initial contract configuration parameters
* @param _loanTokenAddress order type supported by the token.
*/
constructor(string _loanTokenName, address _loanTokenAddress, address _maker) public {
require(bytes(_loanTokenName).length > 0 && _maker != address(0));
if (!_loanTokenName.stringCompare(TOKEN_ETH)) {
require(_loanTokenAddress != address(0));
token20 = _loanTokenAddress;
}
toTime = now;
maker = _maker;
loanTokenName = _loanTokenName;
status = StatusChoices.NO_LOAN;
}
/**
* @dev Complete an order combination and issue the loan to the borrower.
* @param _taker address of investor.
* @param _toTime order repayment due date.
* @param _repaymentSum total amount of money that the borrower ultimately needs to return.
*/
function takerOrder(address _taker, uint32 _toTime, uint256 _repaymentSum) public onlyOwnerOrPartner {
require(_taker != address(0) && _toTime > 0 && now <= _toTime && _repaymentSum > 0 && status == StatusChoices.NO_LOAN);
taker = _taker;
toTime = _toTime;
repaymentSum = _repaymentSum;
// Transfer the token provided by the investor to the borrower's address
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(ethAmount[_taker] > 0 && address(this).balance > 0);
outLoanSum = address(this).balance;
maker.transfer(outLoanSum);
} else {
require(token20 != address(0) && ERC20(token20).balanceOf(address(this)) > 0);
outLoanSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(maker, outLoanSum));
}
// Update contract business execution status.
status = StatusChoices.REPAYMENT_WAITING;
emit TakerOrder(taker, outLoanSum);
}
/**
* @dev Only the full repayment will execute the contract agreement.
*/
function executeOrder() public onlyOwnerOrPartner {
require(now <= toTime && status == StatusChoices.REPAYMENT_WAITING);
// The borrower pays off the loan and performs two-way operation.
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(ethAmount[maker] >= repaymentSum && address(this).balance >= repaymentSum);
lastRepaymentSum = address(this).balance;
taker.transfer(repaymentSum);
} else {
require(ERC20(token20).balanceOf(address(this)) >= repaymentSum);
lastRepaymentSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(taker, repaymentSum));
}
PledgeContract(owner)._conclude();
status = StatusChoices.REPAYMENT_ALL;
emit ExecuteOrder(maker, lastRepaymentSum);
}
/**
* @dev Close position or due repayment operation.
*/
function forceCloseOrder() public onlyOwnerOrPartner {
require(status == StatusChoices.REPAYMENT_WAITING);
uint256 transferSum = 0;
if (now <= toTime) {
status = StatusChoices.CLOSE_POSITION;
} else {
status = StatusChoices.OVERDUE_STOP;
}
if(loanTokenName.stringCompare(TOKEN_ETH)){
if(ethAmount[maker] > 0 && address(this).balance > 0){
transferSum = address(this).balance;
maker.transfer(transferSum);
}
}else{
if(ERC20(token20).balanceOf(address(this)) > 0){
transferSum = ERC20(token20).balanceOf(address(this));
require(safeErc20Transfer(maker, transferSum));
}
}
// Return pledge token.
PledgeContract(owner)._forceConclude(taker);
emit ForceCloseOrder(toTime, transferSum);
}
/**
* @dev Withdrawal of the token invested by the taker.
* @param _taker address of investor.
* @param _refundSum refundSum number of tokens withdrawn.
*/
function withdrawToken(address _taker, uint256 _refundSum) public onlyOwnerOrPartner {
require(status == StatusChoices.NO_LOAN);
require(_taker != address(0) && _refundSum > 0);
if (loanTokenName.stringCompare(TOKEN_ETH)) {
require(address(this).balance >= _refundSum && ethAmount[_taker] >= _refundSum);
_taker.transfer(_refundSum);
ethAmount[_taker] = ethAmount[_taker].sub(_refundSum);
} else {
require(ERC20(token20).balanceOf(address(this)) >= _refundSum);
require(safeErc20Transfer(_taker, _refundSum));
}
emit WithdrawToken(_taker, _refundSum);
}
/**
* @dev Since the implementation of usdt ERC20.sol transfer code does not design the return value,
* @dev which is different from most ERC20 token interfaces,most erc20 transfer token agreements return bool.
* @dev it is necessary to independently adapt the interface for usdt token in order to transfer successfully
* @dev if not, the transfer may fail.
*/
function safeErc20Transfer(address _toAddress,uint256 _transferSum) internal returns (bool) {
if(loanTokenName.stringCompare(TOKEN_USDT)){
UsdtERC20(token20).transfer(_toAddress, _transferSum);
}else{
require(ERC20(token20).transfer(_toAddress, _transferSum));
}
return true;
}
/**
* @dev Get current contract order status.
*/
function getPledgeStatus() public view returns(string pledgeStatus) {
if (status == StatusChoices.NO_LOAN) {
pledgeStatus = "NO_LOAN";
} else if (status == StatusChoices.REPAYMENT_WAITING) {
pledgeStatus = "REPAYMENT_WAITING";
} else if (status == StatusChoices.REPAYMENT_ALL) {
pledgeStatus = "REPAYMENT_ALL";
} else if (status == StatusChoices.CLOSE_POSITION) {
pledgeStatus = "CLOSE_POSITION";
} else {
pledgeStatus = "OVERDUE_STOP";
}
}
}
/**
* @title EscrowMaintainContract
* @dev Provides configuration and external interfaces.
*/
contract EscrowMaintainContract is PartnerAuthority {
address public pledgeFactory;
// map of token name to token pool address;
mapping(string => address) internal nameByPool;
// map of token name to erc20 token address;
mapping(string => address) internal nameByToken;
// -----------------------------------------
// External interface
// -----------------------------------------
/**
* @dev Create a pledge subcontract
* @param _pledgeId index number of the pledge contract.
*/
function createPledgeContract(uint256 _pledgeId) public onlyPartner returns(bool) {
require(_pledgeId > 0 && pledgeFactory!=address(0));
require(PledgeFactory(pledgeFactory).createPledgeContract(_pledgeId,partner));
return true;
}
/**
* @dev Batch create a pledge subcontract
* @param _pledgeIds index number of the pledge contract.
*/
function batchCreatePledgeContract(uint256[] _pledgeIds) public onlyPartner {
require(_pledgeIds.length > 0);
PledgeFactory(pledgeFactory).batchCreatePledgeContract(_pledgeIds,partner);
}
/**
* @dev Use the index to get the basic information of the corresponding pledge contract.
* @param _pledgeId index number of the pledge contract
*/
function getEscrowPledge(uint256 _pledgeId) public view returns(string tokenName, address pledgeContract) {
require(_pledgeId > 0);
(tokenName,pledgeContract) = PledgeFactory(pledgeFactory).getEscrowPledge(_pledgeId);
}
/**
* @dev setTokenPool, set the token pool contract address of a token name.
* @param _tokenName set token pool name.
* @param _address the token pool contract address.
*/
function setTokenPool(string _tokenName, address _address) public onlyOwner {
require(_address != address(0) && bytes(_tokenName).length > 0);
nameByPool[_tokenName] = _address;
}
/**
* @dev setToken, set the token contract address of a token name.
* @param _tokenName token name
* @param _address the ERC20 token contract address.
*/
function setToken(string _tokenName, address _address) public onlyOwner {
require(_address != address(0) && bytes(_tokenName).length > 0);
nameByToken[_tokenName] = _address;
}
/**
* @dev setPledgeFactory, Plant contract for configuration management pledge business.
* @param _factory pledge factory contract.
*/
function setPledgeFactory(address _factory) public onlyOwner {
require(_factory != address(0));
pledgeFactory = _factory;
}
/**
* @dev Checks whether the current token pool is supported.
* @param _tokenName token name
*/
function includeTokenPool(string _tokenName) view public returns(address) {
require(bytes(_tokenName).length > 0);
return nameByPool[_tokenName];
}
/**
* @dev Checks whether the current erc20 token is supported.
* @param _tokenName token name
*/
function includeToken(string _tokenName) view public returns(address) {
require(bytes(_tokenName).length > 0);
return nameByToken[_tokenName];
}
}
/**
* @title PledgeContract
* @dev Pledge process management contract
*/
contract PledgeContract is PartnerAuthority {
using SafeMath for uint256;
using SafeCompare for string;
/**
* @dev Type of execution state of the pledge contract(irreversible)
*/
enum StatusChoices {
NO_PLEDGE_INFO,
PLEDGE_CREATE_MATCHING,
PLEDGE_REFUND
}
string public pledgeTokenName;
uint256 public pledgeId;
address internal maker;
address internal token20;
address internal factory;
address internal escrowContract;
uint256 internal pledgeAccountSum;
// order contract address
address internal orderContract;
string internal loanTokenName;
StatusChoices internal status;
address internal tokenPoolAddress;
string internal constant TOKEN_ETH = "ETH";
string internal constant TOKEN_USDT = "USDT";
// ETH pledge account
mapping(address => uint256) internal verifyEthAccount;
/**
* Event for createOrderContract logging.
* @param newOrderContract management contract address.
*/
event CreateOrderContract(address newOrderContract);
/**
* Event for WithdrawToken logging.
* @param maker address of investor.
* @param pledgeTokenName token name.
* @param refundSum number of tokens withdrawn.
*/
event WithdrawToken(address indexed maker, string pledgeTokenName, uint256 refundSum);
/**
* Event for appendEscrow logging.
* @param maker address of borrower.
* @param appendSum append amount.
*/
event AppendEscrow(address indexed maker, uint256 appendSum);
/**
* @dev Constructor initial contract configuration parameters
*/
constructor(uint256 _pledgeId, address _factory , address _escrowContract) public {
require(_pledgeId > 0 && _factory != address(0) && _escrowContract != address(0));
pledgeId = _pledgeId;
factory = _factory;
status = StatusChoices.NO_PLEDGE_INFO;
escrowContract = _escrowContract;
}
// -----------------------------------------
// external interface
// -----------------------------------------
function() external payable {
require(status != StatusChoices.PLEDGE_REFUND);
// Identify the borrower.
if (maker != address(0)) {
require(address(msg.sender) == maker);
}
// Record basic information about the borrower's pledge ETH
verifyEthAccount[msg.sender] = verifyEthAccount[msg.sender].add(msg.value);
}
/**
* @dev Add the pledge information and transfer the pledged token into the corresponding currency pool.
* @param _pledgeTokenName maker pledge token name.
* @param _maker borrower address.
* @param _pledgeSum pledge amount.
* @param _loanTokenName pledge token type.
*/
function addRecord(string _pledgeTokenName, address _maker, uint256 _pledgeSum, string _loanTokenName) public onlyOwner {
require(_maker != address(0) && _pledgeSum > 0 && status != StatusChoices.PLEDGE_REFUND);
// Add the pledge information for the first time.
if (status == StatusChoices.NO_PLEDGE_INFO) {
// public data init.
maker = _maker;
pledgeTokenName = _pledgeTokenName;
tokenPoolAddress = checkedTokenPool(pledgeTokenName);
PledgeFactory(factory).updatePledgeType(pledgeId, pledgeTokenName);
// Assign rights to the operation of the contract pool
PledgeFactory(factory).tokenPoolOperater(tokenPoolAddress, address(this));
// Create order management contracts.
createOrderContract(_loanTokenName);
}
// Record information of each pledge.
pledgeAccountSum = pledgeAccountSum.add(_pledgeSum);
PledgePoolBase(tokenPoolAddress).addRecord(maker, pledgeAccountSum, pledgeId, pledgeTokenName);
// Transfer the pledge token to the appropriate token pool.
if (pledgeTokenName.stringCompare(TOKEN_ETH)) {
require(verifyEthAccount[maker] >= _pledgeSum);
tokenPoolAddress.transfer(_pledgeSum);
} else {
token20 = checkedToken(pledgeTokenName);
require(ERC20(token20).balanceOf(address(this)) >= _pledgeSum);
require(safeErc20Transfer(token20,tokenPoolAddress, _pledgeSum));
}
}
/**
* @dev Increase the number of pledged tokens.
* @param _appendSum append amount.
*/
function appendEscrow(uint256 _appendSum) public onlyOwner {
require(status == StatusChoices.PLEDGE_CREATE_MATCHING);
addRecord(pledgeTokenName, maker, _appendSum, loanTokenName);
emit AppendEscrow(maker, _appendSum);
}
/**
* @dev Withdraw pledge behavior.
* @param _maker borrower address.
*/
function withdrawToken(address _maker) public onlyOwner {
require(status != StatusChoices.PLEDGE_REFUND);
uint256 pledgeSum = 0;
// there are two types of retractions.
if (status == StatusChoices.NO_PLEDGE_INFO) {
pledgeSum = classifySquareUp(_maker);
} else {
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).withdrawToken(pledgeId, maker, pledgeAccountSum));
pledgeSum = pledgeAccountSum;
}
emit WithdrawToken(_maker, pledgeTokenName, pledgeSum);
}
/**
* @dev Executed in some extreme unforsee cases, to avoid eth locked.
* @param _tokenName recycle token type.
* @param _amount Number of eth to recycle.
*/
function recycle(string _tokenName, uint256 _amount) public onlyOwner {
require(status != StatusChoices.NO_PLEDGE_INFO && _amount>0);
if (_tokenName.stringCompare(TOKEN_ETH)) {
require(address(this).balance >= _amount);
owner.transfer(_amount);
} else {
address token = checkedToken(_tokenName);
require(ERC20(token).balanceOf(address(this)) >= _amount);
require(safeErc20Transfer(token,owner, _amount));
}
}
/**
* @dev Since the implementation of usdt ERC20.sol transfer code does not design the return value,
* @dev which is different from most ERC20 token interfaces,most erc20 transfer token agreements return bool.
* @dev it is necessary to independently adapt the interface for usdt token in order to transfer successfully
* @dev if not, the transfer may fail.
*/
function safeErc20Transfer(address _token20,address _toAddress,uint256 _transferSum) internal returns (bool) {
if(loanTokenName.stringCompare(TOKEN_USDT)){
UsdtERC20(_token20).transfer(_toAddress, _transferSum);
}else{
require(ERC20(_token20).transfer(_toAddress, _transferSum));
}
return true;
}
// -----------------------------------------
// internal interface
// -----------------------------------------
/**
* @dev Create an order process management contract for the match and repayment business.
* @param _loanTokenName expect loan token type.
*/
function createOrderContract(string _loanTokenName) internal {
require(bytes(_loanTokenName).length > 0);
status = StatusChoices.PLEDGE_CREATE_MATCHING;
address loanToken20 = checkedToken(_loanTokenName);
OrderManageContract newOrder = new OrderManageContract(_loanTokenName, loanToken20, maker);
setPartner(address(newOrder));
newOrder.setPartner(owner);
// update contract public data.
orderContract = newOrder;
loanTokenName = _loanTokenName;
emit CreateOrderContract(address(newOrder));
}
/**
* @dev classification withdraw.
* @dev Execute without changing the current contract data state.
* @param _maker borrower address.
*/
function classifySquareUp(address _maker) internal returns(uint256 sum) {
if (pledgeTokenName.stringCompare(TOKEN_ETH)) {
uint256 pledgeSum = verifyEthAccount[_maker];
require(pledgeSum > 0 && address(this).balance >= pledgeSum);
_maker.transfer(pledgeSum);
verifyEthAccount[_maker] = 0;
sum = pledgeSum;
} else {
uint256 balance = ERC20(token20).balanceOf(address(this));
require(balance > 0);
require(safeErc20Transfer(token20,_maker, balance));
sum = balance;
}
}
/**
* @dev Check wether the token is included for a token name.
* @param _tokenName token name.
*/
function checkedToken(string _tokenName) internal view returns(address) {
address tokenAddress = EscrowMaintainContract(escrowContract).includeToken(_tokenName);
require(tokenAddress != address(0));
return tokenAddress;
}
/**
* @dev Check wether the token pool is included for a token name.
* @param _tokenName pledge token name.
*/
function checkedTokenPool(string _tokenName) internal view returns(address) {
address tokenPool = EscrowMaintainContract(escrowContract).includeTokenPool(_tokenName);
require(tokenPool != address(0));
return tokenPool;
}
// -----------------------------------------
// business relationship interface
// (Only the order contract has authority to operate)
// -----------------------------------------
/**
* @dev Refund of the borrower’s pledge.
*/
function _conclude() public onlyPartner {
require(status == StatusChoices.PLEDGE_CREATE_MATCHING);
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).refundTokens(pledgeId, pledgeAccountSum, maker));
}
/**
* @dev Expired for repayment or close position.
* @param _taker address of investor.
*/
function _forceConclude(address _taker) public onlyPartner {
require(_taker != address(0) && status == StatusChoices.PLEDGE_CREATE_MATCHING);
status = StatusChoices.PLEDGE_REFUND;
require(PledgePoolBase(tokenPoolAddress).refundTokens(pledgeId, pledgeAccountSum, _taker));
}
// -----------------------------------------
// query interface (use no gas)
// -----------------------------------------
/**
* @dev Get current contract order status.
* @return pledgeStatus state indicate.
*/
function getPledgeStatus() public view returns(string pledgeStatus) {
if (status == StatusChoices.NO_PLEDGE_INFO) {
pledgeStatus = "NO_PLEDGE_INFO";
} else if (status == StatusChoices.PLEDGE_CREATE_MATCHING) {
pledgeStatus = "PLEDGE_CREATE_MATCHING";
} else {
pledgeStatus = "PLEDGE_REFUND";
}
}
/**
* @dev get order contract address. use no gas.
*/
function getOrderContract() public view returns(address) {
return orderContract;
}
/**
* @dev Gets the total number of tokens pledged under the current contract.
*/
function getPledgeAccountSum() public view returns(uint256) {
return pledgeAccountSum;
}
/**
* @dev get current contract borrower address.
*/
function getMakerAddress() public view returns(address) {
return maker;
}
/**
* @dev get current contract pledge Id.
*/
function getPledgeId() external view returns(uint256) {
return pledgeId;
}
}
/**
* @title PledgeFactory
* @dev Pledge factory contract.
* @dev Specially provides the pledge guarantee creation and the statistics function.
*/
contract PledgeFactory is RBACOperator {
using AddressUtils for address;
// initial type of pledge contract.
string internal constant INIT_TOKEN_NAME = "UNKNOWN";
mapping(uint256 => EscrowPledge) internal pledgeEscrowById;
// pledge number unique screening.
mapping(uint256 => bool) internal isPledgeId;
/**
* @dev Pledge guarantee statistics.
*/
struct EscrowPledge {
address pledgeContract;
string tokenName;
}
/**
* Event for createOrderContract logging.
* @param pledgeId management contract id.
* @param newPledgeAddress pledge management contract address.
*/
event CreatePledgeContract(uint256 indexed pledgeId, address newPledgeAddress);
/**
* @dev Create a pledge subcontract
* @param _pledgeId index number of the pledge contract.
*/
function createPledgeContract(uint256 _pledgeId, address _escrowPartner) public onlyPartner returns(bool) {
require(_pledgeId > 0 && !isPledgeId[_pledgeId] && _escrowPartner!=address(0));
// Give the pledge contract the right to update statistics.
PledgeContract pledgeAddress = new PledgeContract(_pledgeId, address(this),partner);
pledgeAddress.transferOwnership(_escrowPartner);
addOperater(address(pledgeAddress));
// update pledge contract info
isPledgeId[_pledgeId] = true;
pledgeEscrowById[_pledgeId] = EscrowPledge(pledgeAddress, INIT_TOKEN_NAME);
emit CreatePledgeContract(_pledgeId, address(pledgeAddress));
return true;
}
/**
* @dev Batch create a pledge subcontract
* @param _pledgeIds index number of the pledge contract.
*/
function batchCreatePledgeContract(uint256[] _pledgeIds, address _escrowPartner) public onlyPartner {
require(_pledgeIds.length > 0 && _escrowPartner.isContract());
for (uint i = 0; i < _pledgeIds.length; i++) {
require(createPledgeContract(_pledgeIds[i],_escrowPartner));
}
}
/**
* @dev Use the index to get the basic information of the corresponding pledge contract.
* @param _pledgeId index number of the pledge contract
*/
function getEscrowPledge(uint256 _pledgeId) public view returns(string tokenName, address pledgeContract) {
require(_pledgeId > 0);
tokenName = pledgeEscrowById[_pledgeId].tokenName;
pledgeContract = pledgeEscrowById[_pledgeId].pledgeContract;
}
// -----------------------------------------
// Internal interface (Only the pledge contract has authority to operate)
// -----------------------------------------
/**
* @dev Configure permissions to operate on the token pool.
* @param _tokenPool token pool contract address.
* @param _pledge pledge contract address.
*/
function tokenPoolOperater(address _tokenPool, address _pledge) public hasOperationPermission {
require(_pledge != address(0) && address(msg.sender).isContract() && address(msg.sender) == _pledge);
PledgePoolBase(_tokenPool).addOperater(_pledge);
}
/**
* @dev Update the basic data of the pledge contract.
* @param _pledgeId index number of the pledge contract.
* @param _tokenName pledge contract supported token type.
*/
function updatePledgeType(uint256 _pledgeId, string _tokenName) public hasOperationPermission {
require(_pledgeId > 0 && bytes(_tokenName).length > 0 && address(msg.sender).isContract());
pledgeEscrowById[_pledgeId].tokenName = _tokenName;
}
}
|
Configure permissions to operate on the token pool. _tokenPool token pool contract address. _pledge pledge contract address./
|
function tokenPoolOperater(address _tokenPool, address _pledge) public hasOperationPermission {
require(_pledge != address(0) && address(msg.sender).isContract() && address(msg.sender) == _pledge);
PledgePoolBase(_tokenPool).addOperater(_pledge);
}
| 6,378,430
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import './DateTimeLibrary.sol';
contract LXRNFT is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string baseURI;
uint mintPhases;
int usdPerNft;
address lxrgame;
mapping(address => bool) private whitelist;
mapping(address => uint) private _tokenCount;
mapping (uint256 => TokenMeta) private _tokenMeta;
AggregatorV3Interface internal priceFeedUsd;
struct TokenMeta {
uint256 id;
uint256 price;
uint power;
bool sale;
uint locktime;
}
/**
* Chainlink for Oracle in BSC
* Network: Binance Smart Chain
* Aggregator 1: BNB/USD
* Address: 0x0567F2323251f0Aab15c8dFb1967E4e8A7D42aeE (Mainnet)
* Address: 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526 (Testnet)
* Aggregator 2: BNB/LXR
* Address: 0x0 (Mainnet)
* Address: 0x0 (Testnet)
* Reference: https://docs.chain.link/docs/binance-smart-chain-addresses/
*/
constructor() ERC721("Loxarian NFT", "LXRT") {
baseURI = "http://partybeavers.io:8080/token/";
usdPerNft = 200; // 200 usd
mintPhases = 0; // 0: whitelist Sale, 1: public Sale, 2: normal Minting
priceFeedUsd = AggregatorV3Interface(0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override {
require(_tokenMeta[tokenId].locktime == 0 || _tokenMeta[tokenId].locktime < block.timestamp, "Token locked");
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view override virtual returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) public virtual onlyOwner {
baseURI = _newBaseURI;
}
function setLoxarGame(address _lxrgame) public onlyOwner {
lxrgame = _lxrgame;
}
/**
* @dev Minting Phases for starting Sales.
*/
function setMintPhases(uint _newmintPhases) public onlyOwner {
mintPhases = _newmintPhases;
if (mintPhases > 1) {
usdPerNft = 10;
}
}
function isWhitelist(address sender) public view returns (bool) {
return whitelist[sender];
}
function addWhitelist(address[] memory _whitelist) public onlyOwner {
for (uint i = 0; i < _whitelist.length; i++) {
whitelist[_whitelist[i]] = true;
}
}
function getAllOnSale () public view virtual returns( TokenMeta[] memory ) {
uint256 counter = 0;
for(uint i = 1; i < _tokenIds.current() + 1; i++) {
if(_tokenMeta[i].sale == true) {
counter++;
}
}
TokenMeta[] memory tokensOnSale = new TokenMeta[](counter);
counter = 0;
for(uint i = 1; i < _tokenIds.current() + 1; i++) {
if(_tokenMeta[i].sale == true) {
tokensOnSale[counter] = _tokenMeta[i];
counter++;
}
}
return tokensOnSale;
}
/**
* @dev sets maps token to its price
* @param _tokenId uint256 token ID (token number)
* @param _sale bool token on sale
* @param _price unit256 token price
*
* Requirements:
* `tokenId` must exist
* `price` must be more than 0
* `owner` must the msg.owner
*/
function setTokenSale(uint256 _tokenId, bool _sale, uint256 _price) public {
require(_exists(_tokenId), "No exist token");
require(_price > 0, "Invalid price");
require(ownerOf(_tokenId) == _msgSender());
_tokenMeta[_tokenId].sale = _sale;
_tokenMeta[_tokenId].price = _price;
}
function setTokenLocked(uint256 _tokenId, bool _lock) public {
require(_exists(_tokenId), "No exist token");
require(ownerOf(_tokenId) == _msgSender() || lxrgame == _msgSender(), "Not allowed");
uint locktime = DateTimeLibrary.addDays(block.timestamp, 1);
if (_lock)
_tokenMeta[_tokenId].locktime = locktime;
else
_tokenMeta[_tokenId].locktime = 0;
}
/**
* @dev sets maps token to its price
* @param _tokenId uint256 token ID (token number)
* @param _price uint256 token price
*
* Requirements:
* `tokenId` must exist
* `owner` must the msg.owner
*/
function setTokenPrice(uint256 _tokenId, uint256 _price) public {
require(_exists(_tokenId), "No exist token");
require(ownerOf(_tokenId) == _msgSender());
_tokenMeta[_tokenId].price = _price;
}
function tokenPrice(uint256 tokenId) public view virtual returns (uint256) {
require(_exists(tokenId), "No exist token");
return _tokenMeta[tokenId].price;
}
function tokenMintedCount() public view virtual returns (uint256) {
return _tokenIds.current();
}
function myNFTs() public view virtual returns (uint256[] memory) {
require(msg.sender != address(0), "Invalid address");
uint256 counter = 0;
for(uint i = 1; i < _tokenIds.current() + 1; i++) {
if(msg.sender == ownerOf(i)) {
counter++;
}
}
uint256[] memory mytokens = new uint256[](counter);
counter = 0;
for(uint i = 1; i < _tokenIds.current() + 1; i++) {
if(msg.sender == ownerOf(i)) {
mytokens[counter] = i;
counter++;
}
}
return mytokens;
}
/**
* @dev sets token meta
* @param _tokenId uint256 token ID (token number)
* @param _meta TokenMeta
*
* Requirements:
* `tokenId` must exist
* `owner` must the msg.owner
*/
function _setTokenMeta(uint256 _tokenId, TokenMeta memory _meta) private {
require(_exists(_tokenId), "No exist token");
_tokenMeta[_tokenId] = _meta;
}
function tokenMeta(uint256 _tokenId) public view returns (TokenMeta memory) {
require(_exists(_tokenId), "No exist token");
return _tokenMeta[_tokenId];
}
/**
* @dev purchase _tokenId
* @param _tokenId uint256 token ID (token number)
*/
function purchaseToken(uint256 _tokenId) external payable nonReentrant {
require(msg.sender != address(0) && msg.sender != ownerOf(_tokenId), "Invalid sender");
require(msg.value >= _tokenMeta[_tokenId].price, "Insufficient price");
require(_tokenMeta[_tokenId].sale == true, "Not allowed for sale");
require(mintPhases == 2, "Not allowed now");
address tokenSeller = ownerOf(_tokenId);
// payable(tokenSeller).transfer(msg.value);
(bool bSent, ) = payable(tokenSeller).call{value:msg.value}("");
if (!bSent) {
revert("Failed to send ether");
}
setApprovalForAll(tokenSeller, true);
_transfer(tokenSeller, msg.sender, _tokenId);
_tokenMeta[_tokenId].sale = false;
_tokenCount[tokenSeller]--;
_tokenCount[msg.sender]++;
}
function mintToken() external payable nonReentrant returns (uint256) {
require(msg.sender != address(0), "Invalid sender");
uint _price = uint(_getPrice(usdPerNft));
if (mintPhases == 0) {
require(_tokenIds.current() <= 5000, "Phase 1: overflowed 5000");
require(isWhitelist(msg.sender) == true, "not whitelist address");
require(_tokenCount[msg.sender] < 5, "A whitelist can have maximum 5 NFTs");
}
else if (mintPhases == 1) {
require(_tokenIds.current() <= 10000, "Phase 2: overflowed 10000");
require(_tokenCount[msg.sender] < 10, "A wallet can have maximum 10 NFTs");
}
require(msg.value >= _price, "Insufficient price");
payable(owner()).transfer(msg.value);
setApprovalForAll(owner(), true);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(msg.sender, newItemId);
_tokenCount[msg.sender]++;
_setTokenMeta(newItemId, TokenMeta(newItemId, _price, _generateRandomPower(0), false, 0));
return newItemId;
}
function mintAdmin(address _to, uint256 _count) external onlyOwner
{
require(_to != address(0), "Invalid receiver");
uint _price = uint(_getPrice(usdPerNft));
for (uint256 i; i < _count; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(payable(_to), newItemId);
_tokenCount[_to]++;
_setTokenMeta(newItemId, TokenMeta(newItemId, _price, _generateRandomPower(i), false, 0));
}
}
// Function to generate the hash value
function _generateRandomPower(uint i) internal view returns (uint)
{
uint random = uint(keccak256(abi.encodePacked(block.timestamp, i)));
uint group = uint(random % 100) + 1;
uint power = 100;
uint[] memory provs = new uint[](5);
if (mintPhases == 0) {
provs[0] = 0; provs[1] = 0; provs[2] = 60; provs[3] = 30; provs[4] = 10;
}
else if (mintPhases == 1) {
provs[0] = 0; provs[1] = 75; provs[2] = 17; provs[3] = 6; provs[4] = 2;
}
else {
provs[0] = 75; provs[1] = 17; provs[2] = 6; provs[3] = 2; provs[4] = 0;
}
if (group <= provs[0]) { // basic
power = random % (250 - 100) + 100;
}
else if (group <= (provs[0] + provs[1])) { // advanced
power = random % (500 - 250) + 250;
}
else if (group <= (provs[0] + provs[1] + provs[2])) { // epic
power = random % (1000 - 500) + 500;
}
else if (group <= (provs[0] + provs[1] + provs[2] + provs[3])) { // legendary
power = random % (2000 - 1000) + 1000;
}
else { // supereme
power = random % (3000 - 2000) + 2000;
}
return power;
}
// _usdPrice: USD Price * 100000000
// _return: BNB Price (wei)
function _getPrice(int _usdPrice) public view returns (int)
{
if (mintPhases == 0) {
return 400000000000000000; // 0.4 BNB
}
else if (mintPhases == 1) {
return 150000000000000000; // 0.15 BNB
}
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeedUsd.latestRoundData();
return _usdPrice * (10 ** 26) / price;
}
}
|
sets maps token to its price _tokenId uint256 token ID (token number) _sale bool token on sale _price unit256 token price Requirements: `tokenId` must exist `price` must be more than 0 `owner` must the msg.owner/
|
function setTokenSale(uint256 _tokenId, bool _sale, uint256 _price) public {
require(_exists(_tokenId), "No exist token");
require(_price > 0, "Invalid price");
require(ownerOf(_tokenId) == _msgSender());
_tokenMeta[_tokenId].sale = _sale;
_tokenMeta[_tokenId].price = _price;
}
| 1,755,127
|
pragma solidity ^0.5.0;
contract Wahl{
mapping(address => uint256) vergebbareStimmen;
mapping(string => uint256) vergebeneStimmen;
mapping(string => bool) waehlerKeys; //Oder eine Liste | Inhalt: Schlüssel der Wähler
address wahlleiter;
enum WahlStatus{
initialisieren,
laeuft,
beendet
}
WahlStatus status;
uint256 stimmenAnzahl;
//Initialisierung der Wahl
/**
* Konstruktor.
*/
constructor () public {
wahlleiter = msg.sender;
status = WahlStatus.initialisieren;
stimmenAnzahl = 1;
}
/**
* Setzt die Anzahl der Stimmen, die ein Wähler vergeben kann.
*/
function setStimmenAnzahl(uint256 _stimmenAnzahl) public returns(bool) {
if(msg.sender == wahlleiter&&status == WahlStatus.initialisieren){
stimmenAnzahl = _stimmenAnzahl;
return true;
}
return false;
}
/**
* Fügt einen Schlüssel (Codeword als String) hinzu, den ein Wähler benötigt, um zu wählen
*/
function addWaehler(string memory key) public returns(bool) {
if(msg.sender == wahlleiter&&status == WahlStatus.initialisieren){
waehlerKeys[key] = true;
return true;
}
return false;
}
/**
* Füft eine Wahloption hinzu. Dies kann eine Person, aber auch etwas anderes sein.
*/
function addOption(string memory option) public returns(bool) {
if(msg.sender == wahlleiter&&status == WahlStatus.initialisieren){
vergebeneStimmen[option] = 0;
return true;
}
return false;
}
//Durchführen der Wahl
/**
* Mit dieser Methode wird die Wahl gestartet. Dies bedeutet, dass die
* Initialisiations-Funktionen nicht mehr funktionieren und es möglich
* ist, Stimmen abzugeben.
*/
function wahlStarten() public returns(bool){
if(msg.sender == wahlleiter&&status == WahlStatus.initialisieren){
status = WahlStatus.laeuft;
return true;
}
return false;
}
/**
* Fügt den Account eines Wählers in das Wahlregister ein.
* Dazu muss ein vorher eingestellter Schlüssel angegeben werden.
* Der Schlüssel kann nur einmal verwendet werden.
*/
function identify(string memory key) public returns(bool){
if(waehlerKeys[key] == true&&status == WahlStatus.laeuft){
//wenn ja
vergebbareStimmen[msg.sender] = stimmenAnzahl;
waehlerKeys[key] = false;
return true;
}
return false;
}
/**
* Diese Methode ist für einen Wähler gedacht und vergibt eine Stimme
* für die angegebene Option.
*
* TODO: Was passiert bei Angabe einer falschen Option?
*/
function waehle(string memory option) public returns(bool) {
if(vergebbareStimmen[msg.sender] >= 1&&status == WahlStatus.laeuft){
vergebbareStimmen[msg.sender] -= 1;
vergebeneStimmen[option] += 1;
return true;
}
return false;
}
/**
* Diese Methode ist für einen Wähler gedacht und vergibt _stimmanAnzahl viele
* Stimmen an die gewählte Option.
*
* TODO: Was passiert bei Angabe einer falschen Option?
*/
function waehle(string memory option, uint256 _stimmenAnzahl) public returns(bool) {
if(vergebbareStimmen[msg.sender] >= _stimmenAnzahl&&status == WahlStatus.laeuft){
vergebbareStimmen[msg.sender] -= _stimmenAnzahl;
vergebeneStimmen[option] += _stimmenAnzahl;
return true;
}
return false;
}
//Ende der Wahl
/**
* Diese Methode beendet die Wahl und schaltet das Auslesen der Ergebnisse frei.
* Achtung: Die Ergebnisse sind vorher schon in der Blockchain gespeichert und
* können - wenn auch mit etwas mehr Aufwand als durch die Methode getResults()
* - dort ausgelesen werden.
*/
function wahlBeenden() public returns(bool){
if(msg.sender == wahlleiter){
status = WahlStatus.beendet;
return true;
}
return false;
}
/**
* Gibt die Anzahl der Stimmen, die für die Option option abgegeben worden sind,
* zurück.
*/
function getResults(string memory option) public view returns(uint256){
if(status == WahlStatus.beendet){
return vergebeneStimmen[option];
}
return 0;
}
}
|
Durchführen der Wahl Mit dieser Methode wird die Wahl gestartet. Dies bedeutet, dass die Initialisiations-Funktionen nicht mehr funktionieren und es möglich ist, Stimmen abzugeben./
|
function wahlStarten() public returns(bool){
if(msg.sender == wahlleiter&&status == WahlStatus.initialisieren){
status = WahlStatus.laeuft;
return true;
}
return false;
}
| 6,444,184
|
pragma solidity ^0.4.24;
contract S3Devents {
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// (Solitaire3D long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
}
contract modularLong is S3Devents { }
contract Solitaire3D is modularLong {
using SafeMath for *;
using S3DKeysCalcLong for uint256;
string constant public name = "Solitaire 3D";
string constant public symbol = "Solitaire";
uint256 private rndExtra_ = 30 seconds; // length of the very first ICO
uint256 private rndGap_ = 30 seconds; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 24 hours; // round timer starts at this
uint256 constant private rndInc_ = 60 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
address constant private developer = 0xA7759a5CAcE1a3b54E872879Cf3942C5D4ff5897;
address constant private operator = 0xc3F465FD001f78DCEeF6f47FD18E3B04F95f2337;
uint256 public rID_; // round id number / total rounds that have happened
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (uint256 => S3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => S3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => S3Ddatasets.Round) public round_; // (rID => data) round data
uint256 public pID_;
S3Ddatasets.TeamFee public fee_;
constructor()
public
{
fee_ = S3Ddatasets.TeamFee(50); //20% to pot, 15% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
plyr_[1].addr = 0xA7759a5CAcE1a3b54E872879Cf3942C5D4ff5897;
pIDxAddr_[0xA7759a5CAcE1a3b54E872879Cf3942C5D4ff5897] = 1;
pID_ = 1;
}
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with Solitaire3D
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 0, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
S3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
if (msg.value > 1000000000){
buyCore(_pID, _eventData_);
}else{
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
withdraw();
}
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
S3Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit S3Devents.onWithdrawAndDistribute
(
msg.sender,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit S3Devents.onWithdraw(_pID, msg.sender, _eth, _now);
}
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(90)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) )
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) )
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd))
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return(((((round_[_rID].mask) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000);
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, address)
{
// setup local rID
uint256 _rID = rID_;
return
(
_rID, //0
round_[_rID].keys, //1
round_[_rID].end, //2
round_[_rID].strt, //3
round_[_rID].pot, //4
plyr_[round_[_rID].plyr].addr //5
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyrRnds_[_pID][_rID].keys, //1
plyr_[_pID].win, //2
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //3
plyrRnds_[_pID][_rID].eth //4
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, S3Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit S3Devents.onBuyAndDistribute
(
msg.sender,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function managePlayer(uint256 _pID, S3Ddatasets.EventReturns memory _eventData_)
private
returns (S3Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, S3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
// distribute eth
_eventData_ = distributeExternal(_eth, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
}
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(S3Ddatasets.EventReturns memory _eventData_)
private
returns (S3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of Solitaire3D
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
pID_++;
_pID = pID_;
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(S3Ddatasets.EventReturns memory _eventData_)
private
returns (S3Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community developers, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(90)) / 100;
uint256 _com = (_pot / 20);
uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_com);
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
if (_com > 0) {
developer.transfer(_com);
operator.transfer(_com);
}
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.amountWon = _win;
_eventData_.genAmount = 0;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _eth, S3Ddatasets.EventReturns memory _eventData_)
private
returns(S3Ddatasets.EventReturns)
{
// pay 5% to developer and operator
uint256 _long = _eth / 20;
developer.transfer(_long);
operator.transfer(_long);
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, S3Ddatasets.EventReturns memory _eventData_)
private
returns(S3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fee_.gen)) / 100;
// update eth balance (eth = eth - (dev share + oper share))
_eth = _eth.sub(((_eth.mul(10)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, S3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit S3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount
);
}
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0xA7759a5CAcE1a3b54E872879Cf3942C5D4ff5897,
"only team just can activate"
);
// can only be ran once
require(activated_ == false, "Solitaire3D already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library S3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 potAmount; // amount added to pot
uint256 genAmount;
}
struct Player {
address addr; // player address
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 lrnd; // last round played
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library S3DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
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;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
updates round timer based on number of whole keys bought./ grab time calculate time based on number of keys bought compare to max and set new end time
|
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
| 10,037,658
|
pragma solidity ^0.4.24;
/* _____ ______ ________
* / | / \ / |
* $$$$$ | /$$$$$$ | $$$$$$$$/
* $$ | $$ | $$/ $$ |
* __ $$ | $$ | $$ |
* / | $$ | $$ | __ $$ |
* $$ \__$$ | $$ \__/ | $$ |
* $$ $$/ $$ $$/ $$ |
* $$$$$$/ $$$$$$/ $$/
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization
* control functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public collector;
address public distributor;
address public freezer;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event CollectorshipTransferred(address indexed previousCollector, address indexed newCollector);
event DistributorshipTransferred(address indexed previousDistributor, address indexed newDistributor);
event FreezershipTransferred(address indexed previousFreezer, address indexed newFreezer);
/**
* @dev The Ownable constructor sets the original `owner`, `collector`, `distributor` and `freezer` of the contract to the
* sender account.
*/
constructor() public {
owner = msg.sender;
collector = msg.sender;
distributor = msg.sender;
freezer = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if called by any account other than the collector.
*/
modifier onlyCollector() {
require(msg.sender == collector);
_;
}
/**
* @dev Throws if called by any account other than the distributor.
*/
modifier onlyDistributor() {
require(msg.sender == distributor);
_;
}
/**
* @dev Throws if called by any account other than the freezer.
*/
modifier onlyFreezer() {
require(msg.sender == freezer);
_;
}
/**
* @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(isNonZeroAccount(newOwner));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the owner to transfer control of the contract to a newCollector.
* @param newCollector The address to transfer collectorship to.
*/
function transferCollectorship(address newCollector) onlyOwner public {
require(isNonZeroAccount(newCollector));
emit CollectorshipTransferred(collector, newCollector);
collector = newCollector;
}
/**
* @dev Allows the owner to transfer control of the contract to a newDistributor.
* @param newDistributor The address to transfer distributorship to.
*/
function transferDistributorship(address newDistributor) onlyOwner public {
require(isNonZeroAccount(newDistributor));
emit DistributorshipTransferred(distributor, newDistributor);
distributor = newDistributor;
}
/**
* @dev Allows the owner to transfer control of the contract to a newFreezer.
* @param newFreezer The address to transfer freezership to.
*/
function transferFreezership(address newFreezer) onlyOwner public {
require(isNonZeroAccount(newFreezer));
emit FreezershipTransferred(freezer, newFreezer);
freezer = newFreezer;
}
// check if the given account is valid
function isNonZeroAccount(address _addr) internal pure returns (bool is_nonzero_account) {
return _addr != address(0);
}
}
/**
* @title ERC20
* @dev ERC20 contract interface
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title JCT
* @author Daisuke Hirata & Noriyuki Izawa
* @dev JCT is an ERC20 Token. First envisioned by NANJCOIN
*/
contract JCT is ERC20, Ownable {
using SafeMath for uint256;
string public name = "JCT";
string public symbol = "JCT";
uint8 public decimals = 8;
uint256 public totalSupply = 18e7 * 1e8;
address public relay;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public unlockUnixTime;
event FrozenFunds(address indexed target, bool frozen);
event LockedFunds(address indexed target, uint256 locked);
/**
* @dev Constructor is called only once and can not be called again
*/
constructor(address founder, address _relay) public {
owner = founder;
collector = founder;
distributor = founder;
freezer = founder;
balanceOf[founder] = totalSupply;
relay = _relay;
}
modifier onlyAuthorized() {
require(msg.sender == relay || checkMessageData(msg.sender));
_;
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
/**
* @dev Prevent targets from sending or receiving tokens
* @param targets Addresses to be frozen
* @param isFrozen either to freeze it or not
*/
function freezeAccounts(address[] targets, bool isFrozen) onlyFreezer public {
require(targets.length > 0);
for (uint j = 0; j < targets.length; j++) {
require(isNonZeroAccount(targets[j]));
frozenAccount[targets[j]] = isFrozen;
emit FrozenFunds(targets[j], isFrozen);
}
}
/**
* @dev Prevent targets from sending or receiving tokens by setting Unix times
* @param targets Addresses to be locked funds
* @param unixTimes Unix times when locking up will be finished
*/
function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {
require(hasSameArrayLength(targets, unixTimes));
for(uint j = 0; j < targets.length; j++){
require(unlockUnixTime[targets[j]] < unixTimes[j]);
unlockUnixTime[targets[j]] = unixTimes[j];
emit LockedFunds(targets[j], unixTimes[j]);
}
}
/**
* @dev Standard function transfer with no _data
*/
function transfer(address _to, uint _value) public returns (bool success) {
require(hasEnoughBalance(msg.sender, _value)
&& isAvailableAccount(msg.sender)
&& isAvailableAccount(_to));
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(isNonZeroAccount(_to)
&& hasEnoughBalance(_from, _value)
&& hasEnoughAllowance(_from, msg.sender, _value)
&& isAvailableAccount(_from)
&& isAvailableAccount(_to));
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Allows _spender to spend no more than _value tokens in your behalf
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows _spender to spend no more than _value tokens in your behalf. intended to be called from TxRelay contract
*/
function approveTokenCollection(address _claimedSender, address _spender, uint256 _value) onlyAuthorized public returns (bool success) {
require(isAvailableAccount(_claimedSender)
&& isAvailableAccount(msg.sender));
allowance[_claimedSender][_spender] = _value;
emit Approval(_claimedSender, _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
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
/**
* @dev Function to collect tokens from the list of addresses
*/
function collectTokens(address[] addresses, uint[] amounts) onlyCollector public returns (bool) {
require(hasSameArrayLength(addresses, amounts));
uint256 totalAmount = 0;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0
&& isNonZeroAccount(addresses[j])
&& isAvailableAccount(addresses[j])
&& hasEnoughAllowance(addresses[j], msg.sender, amounts[j]));
require(hasEnoughBalance(addresses[j], amounts[j]));
balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]);
allowance[addresses[j]][msg.sender] = allowance[addresses[j]][msg.sender].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
emit Transfer(addresses[j], msg.sender, amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount);
return true;
}
/**
* @dev Function to distribute tokens to the list of addresses
*/
function distributeTokens(address[] addresses, uint[] amounts) onlyDistributor public returns (bool) {
require(hasSameArrayLength(addresses, amounts)
&& isAvailableAccount(msg.sender));
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& isNonZeroAccount(addresses[j])
&& isAvailableAccount(addresses[j]));
totalAmount = totalAmount.add(amounts[j]);
}
require(hasEnoughBalance(msg.sender, totalAmount));
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
emit Transfer(msg.sender, addresses[j], amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
// check if the given account is available
function isAvailableAccount(address _addr) public view returns (bool is_valid_account) {
return isUnLockedAccount(_addr) && isUnfrozenAccount(_addr);
}
// check if the given account is not locked up
function isUnLockedAccount(address _addr) public view returns (bool is_unlocked_account) {
return now > unlockUnixTime[_addr];
}
// check if the given account is not frozen
function isUnfrozenAccount(address _addr) public view returns (bool is_unfrozen_account) {
return frozenAccount[_addr] == false;
}
// check if the given account has enough balance more than given amount
function hasEnoughBalance(address _addr, uint256 _value) public view returns (bool has_enough_balance) {
return _value > 0 && balanceOf[_addr] >= _value;
}
// check if the given spender has enough allowance of owner more than given amount
function hasEnoughAllowance(address _owner, address _spender, uint256 _value) public view returns (bool has_enough_balance) {
return allowance[_owner][_spender] >= _value;
}
// check if the given account is not frozen
function hasSameArrayLength(address[] addresses, uint[] amounts) private pure returns (bool has_same_array_length) {
return addresses.length > 0 && addresses.length == amounts.length;
}
//Checks that address a is the first input in msg.data.
//Has very minimal gas overhead.
function checkMessageData(address a) private pure returns (bool t) {
if (msg.data.length < 36) return false;
assembly {
let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
t := eq(a, and(mask, calldataload(4)))
}
}
}
|
Function to distribute tokens to the list of addresses/
|
function distributeTokens(address[] addresses, uint[] amounts) onlyDistributor public returns (bool) {
require(hasSameArrayLength(addresses, amounts)
&& isAvailableAccount(msg.sender));
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& isNonZeroAccount(addresses[j])
&& isAvailableAccount(addresses[j]));
totalAmount = totalAmount.add(amounts[j]);
}
require(hasEnoughBalance(msg.sender, totalAmount));
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
emit Transfer(msg.sender, addresses[j], amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
| 6,381,116
|
pragma solidity ^0.4.24;
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;
}
}
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;
}
}
contract Withdrawable is Ownable {
event ReceiveEther(address _from, uint256 _value);
event WithdrawEther(address _to, uint256 _value);
event WithdrawToken(address _token, address _to, uint256 _value);
/**
* @dev recording receiving ether from msn.sender
*/
function () payable public {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev withdraw,send ether to target
* @param _to is where the ether will be sent to
* _amount is the number of the ether
*/
function withdraw(address _to, uint _amount) public onlyOwner returns (bool) {
require(_to != address(0));
_to.transfer(_amount);
emit WithdrawEther(_to, _amount);
return true;
}
/**
* @dev withdraw tokens, send tokens to target
*
* @param _token the token address that will be withdraw
* @param _to is where the tokens will be sent to
* _value is the number of the token
*/
function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) {
require(_to != address(0));
require(_token != address(0));
ERC20 tk = ERC20(_token);
tk.transfer(_to, _value);
emit WithdrawToken(_token, _to, _value);
return true;
}
/**
* @dev receive approval from an ERC20 token contract, and then gain the tokens,
* then take a record
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 the amounts of tokens to be sent
* @param _token address the ERC20 token address
* @param _extraData bytes the extra data for the record
*/
// function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public {
// require(_token != address(0));
// require(_from != address(0));
// ERC20 tk = ERC20(_token);
// require(tk.transferFrom(_from, this, _value));
// emit ReceiveDeposit(_from, _value, _token, _extraData);
// }
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract LockedStorage is Withdrawable, Claimable {
using SafeMath for uint256;
/**
* account description
*/
struct Account {
string name;
uint256 balance;
uint256 frozen;
}
// record lock time period and related token amount
struct TimeRec {
uint256 amount;
uint256 remain;
uint256 endTime;
uint256 releasePeriodEndTime;
}
mapping (address => Account) accounts;
mapping (address => bool) public frozenAccounts;
address[] accountAddresses;
mapping (address => TimeRec[]) frozenTimes;
uint256 public size;
/**
* @dev add deposit contract address for the default withdraw wallet
*
* @param _wallet the default withdraw wallet address
* @param _name the wallet owner's name
* @param _value the balance of the wallet need to be stored in this contract
*/
function addAccount(address _wallet, string _name, uint256 _value) onlyOwner public returns (bool) {
require(_wallet != address(0));
accounts[_wallet].balance = _value;
accounts[_wallet].frozen = 0;
accounts[_wallet].name = _name;
accountAddresses.push(_wallet);
size = size.add(1);
return true;
}
/**
* @dev remove an address from the account address list
*
* @param _wallet the account address in the list
*/
function removeAccountAddress(address _wallet) internal returns (bool) {
uint i = 0;
for (;i < accountAddresses.length; i = i.add(1)) {
if (accountAddresses[i] == _wallet) {
break;
}
}
if (i >= accountAddresses.length) {
return false;
}
while (i < accountAddresses.length.sub(1)) {
accountAddresses[i] = accountAddresses[i.add(1)];
i = i.add(1);
}
delete accountAddresses[accountAddresses.length.sub(1)];
accountAddresses.length = accountAddresses.length.sub(1);
return true;
}
/**
* @dev remove deposit contract address from storage
*
* @param _wallet the corresponding deposit address
*/
function removeAccount(address _wallet) onlyOwner public returns (bool) {
require(_wallet != address(0));
delete accounts[_wallet];
delete frozenAccounts[_wallet];
removeAccountAddress(_wallet);
size = size.sub(1);
return true;
}
/**
* @dev add a time record of one account
*
* @param _target the account that holds a list of time records which record the freeze period
* @param _value the amount of the tokens
* @param _frozenEndTime the end time of the lock period, unit is second
* @param _releasePeriod the locking period, unit is second
*/
function addLockedTime(address _target,
uint256 _value,
uint256 _frozenEndTime,
uint256 _releasePeriod) onlyOwner public returns (bool) {
require(_target != address(0));
TimeRec[] storage lockedTimes = frozenTimes[_target];
lockedTimes.push(TimeRec(_value, _value, _frozenEndTime, _frozenEndTime.add(_releasePeriod)));
return true;
}
/**
* @dev remove a time records from the time records list of one account
*
* @param _target the account that holds a list of time records which record the freeze period
* @param _ind the account address index
*/
function removeLockedTime(address _target, uint _ind) public returns (bool) {
require(_target != address(0));
TimeRec[] storage lockedTimes = frozenTimes[_target];
require(_ind < lockedTimes.length);
uint256 i = _ind;
while (i < lockedTimes.length.sub(1)) {
lockedTimes[i] = lockedTimes[i.add(1)];
i = i.add(1);
}
delete lockedTimes[lockedTimes.length.sub(1)];
lockedTimes.length = lockedTimes.length.sub(1);
return true;
}
/**
* @dev increase balance of this deposit address
*
* @param _wallet the corresponding wallet address
* @param _value the amount that the balance will be increased
*/
function increaseBalance(address _wallet, uint256 _value) public returns (bool) {
require(_wallet != address(0));
uint256 _balance = accounts[_wallet].balance;
accounts[_wallet].balance = _balance.add(_value);
return true;
}
/**
* @dev decrease balance of this deposit address
*
* @param _wallet the corresponding wallet address
* @param _value the amount that the balance will be decreased
*/
function decreaseBalance(address _wallet, uint256 _value) public returns (bool) {
require(_wallet != address(0));
uint256 _balance = accounts[_wallet].balance;
accounts[_wallet].balance = _balance.sub(_value);
return true;
}
/**
* @dev freeze the tokens in the deposit address
*
* @param _wallet the wallet address
* @param _freeze to freeze or release
* @param _value the amount of tokens need to be frozen
*/
function freezeTokens(address _wallet, bool _freeze, uint256 _value) onlyOwner public returns (bool) {
require(_wallet != address(0));
// require(_value <= balanceOf(_deposit));
frozenAccounts[_wallet] = _freeze;
uint256 _frozen = accounts[_wallet].frozen;
uint256 _balance = accounts[_wallet].balance;
uint256 freezeAble = _balance.sub(_frozen);
if (_freeze) {
if (_value > freezeAble) {
_value = freezeAble;
}
accounts[_wallet].frozen = _frozen.add(_value);
} else {
if (_value > _frozen) {
_value = _frozen;
}
accounts[_wallet].frozen = _frozen.sub(_value);
}
return true;
}
/**
* @dev get the balance of the deposit account
*
* @param _wallet the wallet address
*/
function isExisted(address _wallet) public view returns (bool) {
require(_wallet != address(0));
return (accounts[_wallet].balance != 0);
}
/**
* @dev get the wallet name for the deposit address
*
* @param _wallet the deposit address
*/
function walletName(address _wallet) onlyOwner public view returns (string) {
require(_wallet != address(0));
return accounts[_wallet].name;
}
/**
* @dev get the balance of the deposit account
*
* @param _wallet the deposit address
*/
function balanceOf(address _wallet) public view returns (uint256) {
require(_wallet != address(0));
return accounts[_wallet].balance;
}
/**
* @dev get the frozen amount of the deposit address
*
* @param _wallet the deposit address
*/
function frozenAmount(address _wallet) public view returns (uint256) {
require(_wallet != address(0));
return accounts[_wallet].frozen;
}
/**
* @dev get the account address by index
*
* @param _ind the account address index
*/
function addressByIndex(uint256 _ind) public view returns (address) {
return accountAddresses[_ind];
}
/**
* @dev set the new endtime of the released time of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
* @param _newEndTime the new endtime for the lock period
*/
function changeEndTime(address _target, uint256 _ind, uint256 _newEndTime) onlyOwner public returns (bool) {
require(_target != address(0));
require(_newEndTime > 0);
if (isExisted(_target)) {
TimeRec storage timePair = frozenTimes[_target][_ind];
timePair.endTime = _newEndTime;
return true;
}
return false;
}
/**
* @dev set the new released period end time of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
* @param _newReleaseEndTime the new endtime for the releasing period
*/
function setNewReleaseEndTime(address _target, uint256 _ind, uint256 _newReleaseEndTime) onlyOwner public returns (bool) {
require(_target != address(0));
require(_newReleaseEndTime > 0);
if (isExisted(_target)) {
TimeRec storage timePair = frozenTimes[_target][_ind];
timePair.releasePeriodEndTime = _newReleaseEndTime;
return true;
}
return false;
}
/**
* @dev decrease the remaining locked amount of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
*/
function decreaseRemainLockedOf(address _target, uint256 _ind, uint256 _value) onlyOwner public returns (bool) {
require(_target != address(0));
if (isExisted(_target)) {
TimeRec storage timePair = frozenTimes[_target][_ind];
timePair.remain = timePair.remain.sub(_value);
return true;
}
return false;
}
/**
* @dev get the locked stages of an account
*
* @param _target the owner of some amount of tokens
*/
function lockedStagesNum(address _target) public view returns (uint) {
require(_target != address(0));
return (isExisted(_target) ? frozenTimes[_target].length : 0);
}
/**
* @dev get the endtime of the locked stages of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
*/
function endTimeOfStage(address _target, uint _ind) public view returns (uint256) {
require(_target != address(0));
if (isExisted(_target)) {
TimeRec memory timePair = frozenTimes[_target][_ind];
return timePair.endTime;
}
return 0;
}
/**
* @dev get the remain unrleased tokens of the locked stages of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
*/
function remainOfStage(address _target, uint _ind) public view returns (uint256) {
require(_target != address(0));
if (isExisted(_target)) {
TimeRec memory timePair = frozenTimes[_target][_ind];
return timePair.remain;
}
return 0;
}
/**
* @dev get the remain unrleased tokens of the locked stages of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
*/
function amountOfStage(address _target, uint _ind) public view returns (uint256) {
require(_target != address(0));
if (isExisted(_target)) {
TimeRec memory timePair = frozenTimes[_target][_ind];
return timePair.amount;
}
return 0;
}
/**
* @dev get the remain releasing period end time of an account
*
* @param _target the owner of some amount of tokens
* @param _ind the stage index of the locked stage
*/
function releaseEndTimeOfStage(address _target, uint _ind) public view returns (uint256) {
require(_target != address(0));
if (isExisted(_target)) {
TimeRec memory timePair = frozenTimes[_target][_ind];
return timePair.releasePeriodEndTime;
}
return 0;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
|
decrease balance of this deposit address _wallet the corresponding wallet address _value the amount that the balance will be decreased/
|
function decreaseBalance(address _wallet, uint256 _value) public returns (bool) {
require(_wallet != address(0));
uint256 _balance = accounts[_wallet].balance;
accounts[_wallet].balance = _balance.sub(_value);
return true;
}
| 1,045,681
|
./partial_match/1/0xCa591346A311A372a20ed69e08bBE5107979e243/sources/StakingRewardsAdapterRegistry.sol
|
Update the info of a valid adapter. adapter The adapter to be updating info. info New info to be updated./
|
function updateInfo(address adapter, bytes32 info) external onlyOwner {
require(adapter != address(0), "zero address");
require(info != bytes32(0), "update info to 0 is prohibited");
require(adapters[adapter] != bytes32(0), "no registration");
require(adapters[adapter] != DEPRECATED, "unregistered");
adapters[adapter] = info;
}
| 3,666,127
|
pragma solidity ^0.5.17;
library SafeMath {
function ADD171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB705(a, b, "SafeMath: subtraction overflow");
}
function SUB705(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 MUL180(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 DIV369(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV369(a, b, "SafeMath: division by zero");
}
function DIV369(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 MOD90(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD90(a, b, "SafeMath: modulo by zero");
}
function MOD90(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function TRANSFER190(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE617(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM76(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY562() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF573(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE952(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER195(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL248(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract MatrixErc20 {
using SafeMath for uint;
address public ownerWallet;
struct UserStruct {
bool isExist;
uint id;
mapping (address => uint256) tokenRewards;
mapping (address => uint) referrerID; //Token address to Referrer ID
mapping (address => address[]) referral; //Token address to list of addresses
mapping(address => mapping(uint => uint)) levelExpired; //Token address to level number to expiration date
}
uint REFERRER_1_LEVEL_LIMIT = 5;
uint PERIOD_LENGTH = 180 days;
uint ADMIN_FEE_PERCENTAGE = 10;
mapping(address => mapping(uint => uint)) public LEVEL_PRICE; //Token address to level number to price
mapping (address => UserStruct) public users;
mapping (uint => address) public userList;
uint public currUserID = 0;
mapping (address => bool) public tokens;
mapping (address => uint256) public ownerFees;
event REGLEVELEVENT510(address indexed _user, address indexed _referrer, uint _time, address _token); //inject NONSTANDARD NAMING
event BUYLEVELEVENT399(address indexed _user, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING
event PROLONGATELEVELEVENT866(address indexed _user, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING
event GETMONEYFORLEVELEVENT355(address indexed _user, address indexed _referral, uint _level, address _token); //inject NONSTANDARD NAMING
event LOSTMONEYFORLEVELEVENT103(address indexed _user, address indexed _referral, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING
function SETPERIODLENGTH571(uint _periodLength) public ONLYOWNER423 { //inject NONSTANDARD NAMING
PERIOD_LENGTH = _periodLength;
}
function SETADMINFEEPERCENTAGE408(uint _adminFeePercentage) public ONLYOWNER423 { //inject NONSTANDARD NAMING
require (_adminFeePercentage >= 0 && _adminFeePercentage <= 100, "Fee must be between 0 and 100");
ADMIN_FEE_PERCENTAGE = _adminFeePercentage;
}
function TOGGLETOKEN328(address _token, bool _enabled) public ONLYOWNER423 { //inject NONSTANDARD NAMING
tokens[_token] = _enabled;
if (_enabled) {
for(uint i = 1; i <= 10; i++) {
users[ownerWallet].levelExpired[_token][i] = 55555555555;
}
users[ownerWallet].referrerID[_token] = 0;
}
}
function SETTOKENPRICEATLEVEL23(address _token, uint _level, uint _price) public ONLYOWNER423 { //inject NONSTANDARD NAMING
require(_level > 0 && _level <= 10, "Invalid level");
LEVEL_PRICE[_token][_level] = _price;
}
function SETTOKENPRICE69(address _token, uint _price1, uint _price2, uint _price3, uint _price4, uint _price5, uint _price6, uint _price7, uint _price8, uint _price9, uint _price10) public ONLYOWNER423 { //inject NONSTANDARD NAMING
LEVEL_PRICE[_token][1] = _price1;
LEVEL_PRICE[_token][2] = _price2;
LEVEL_PRICE[_token][3] = _price3;
LEVEL_PRICE[_token][4] = _price4;
LEVEL_PRICE[_token][5] = _price5;
LEVEL_PRICE[_token][6] = _price6;
LEVEL_PRICE[_token][7] = _price7;
LEVEL_PRICE[_token][8] = _price8;
LEVEL_PRICE[_token][9] = _price9;
LEVEL_PRICE[_token][10] = _price10;
if (!tokens[_token]) {
TOGGLETOKEN328(_token, true);
}
}
constructor() public {
ownerWallet = msg.sender;
UserStruct memory userStruct;
currUserID++;
userStruct = UserStruct({
isExist: true,
id: currUserID
});
users[ownerWallet] = userStruct;
userList[currUserID] = ownerWallet;
}
modifier ONLYOWNER423() { //inject NONSTANDARD NAMING
require(msg.sender == ownerWallet, 'caller must be the owner');
_;
}
//Use this before going live to avoid issues
function TRANSFEROWNERSHIP988(address newOwner) public ONLYOWNER423 { //inject NONSTANDARD NAMING
require(newOwner != address(0), 'new owner is the zero address');
require(!users[newOwner].isExist, 'new owner needs to be a new address');
UserStruct memory userStruct = UserStruct({
isExist: true,
id: 1
});
users[newOwner] = userStruct;
userList[1] = newOwner;
delete users[ownerWallet];
ownerWallet = newOwner;
}
function REGUSER700(address _token, uint _referrerID) public payable { //inject NONSTANDARD NAMING
require(tokens[_token], "Token is not enabled");
require(!users[msg.sender].isExist, 'User exist');
require(_referrerID > 0 && _referrerID <= currUserID, 'Incorrect referrer Id');
IERC20 token = IERC20(_token);
require(token.TRANSFERFROM76(msg.sender, address(this), LEVEL_PRICE[_token][1]), "Couldn't take the tokens from the sender");
if(users[userList[_referrerID]].referral[_token].length >= REFERRER_1_LEVEL_LIMIT) _referrerID = users[FINDFREEREFERRER993(_token, userList[_referrerID])].id;
UserStruct memory userStruct;
currUserID++;
userStruct = UserStruct({
isExist: true,
id: currUserID
});
users[msg.sender] = userStruct;
users[msg.sender].referrerID[_token] = _referrerID;
userList[currUserID] = msg.sender;
users[msg.sender].levelExpired[_token][1] = now + PERIOD_LENGTH;
users[userList[_referrerID]].referral[_token].push(msg.sender);
PAYFORLEVEL516(_token, 1, msg.sender);
emit REGLEVELEVENT510(msg.sender, userList[_referrerID], now, _token);
}
function BUYLEVEL817(address _token, uint _level) public payable { //inject NONSTANDARD NAMING
require(users[msg.sender].isExist, 'User not exist');
require(_level > 0 && _level <= 10, 'Incorrect level');
require(tokens[_token], "Token is not enabled");
IERC20 token = IERC20(_token);
require(token.TRANSFERFROM76(msg.sender, address(this), LEVEL_PRICE[_token][_level]), "Couldn't take the tokens from the sender");
if(_level == 1) {
users[msg.sender].levelExpired[_token][1] += PERIOD_LENGTH;
}
else {
for(uint l =_level - 1; l > 0; l--) require(users[msg.sender].levelExpired[_token][l] >= now, 'Buy the previous level');
if(users[msg.sender].levelExpired[_token][_level] == 0) users[msg.sender].levelExpired[_token][_level] = now + PERIOD_LENGTH;
else users[msg.sender].levelExpired[_token][_level] += PERIOD_LENGTH;
}
PAYFORLEVEL516(_token, _level, msg.sender);
emit BUYLEVELEVENT399(msg.sender, _level, now, _token);
}
function GETREFERERINTREE743(address _token, uint _level, address _user) internal view returns(address) { //inject NONSTANDARD NAMING
address referer;
address referer1;
address referer2;
address referer3;
address referer4;
if(_level == 1 || _level == 6) {
referer = userList[users[_user].referrerID[_token]];
}
else if(_level == 2 || _level == 7) {
referer1 = userList[users[_user].referrerID[_token]];
referer = userList[users[referer1].referrerID[_token]];
}
else if(_level == 3 || _level == 8) {
referer1 = userList[users[_user].referrerID[_token]];
referer2 = userList[users[referer1].referrerID[_token]];
referer = userList[users[referer2].referrerID[_token]];
}
else if(_level == 4 || _level == 9) {
referer1 = userList[users[_user].referrerID[_token]];
referer2 = userList[users[referer1].referrerID[_token]];
referer3 = userList[users[referer2].referrerID[_token]];
referer = userList[users[referer3].referrerID[_token]];
}
else if(_level == 5 || _level == 10) {
referer1 = userList[users[_user].referrerID[_token]];
referer2 = userList[users[referer1].referrerID[_token]];
referer3 = userList[users[referer2].referrerID[_token]];
referer4 = userList[users[referer3].referrerID[_token]];
referer = userList[users[referer4].referrerID[_token]];
}
if(!users[referer].isExist) referer = userList[1];
return referer;
}
function PAYFORLEVEL516(address _token, uint _level, address _user) internal { //inject NONSTANDARD NAMING
address referer = GETREFERERINTREE743(_token, _level, _user);
if(users[referer].levelExpired[_token][_level] >= now) {
uint levelPrice = LEVEL_PRICE[_token][_level];
uint payToOwner = levelPrice.MUL180(ADMIN_FEE_PERCENTAGE).DIV369(100);
uint payToReferrer = levelPrice.SUB705(payToOwner);
users[address(uint160(referer))].tokenRewards[_token] = users[address(uint160(referer))].tokenRewards[_token].ADD171(payToReferrer);
ownerFees[_token] = ownerFees[_token].ADD171(payToOwner);
emit GETMONEYFORLEVELEVENT355(referer, msg.sender, _level, _token);
}
else {
emit LOSTMONEYFORLEVELEVENT103(referer, msg.sender, _level, now, _token);
PAYFORLEVEL516(_token, _level, referer);
}
}
function FINDFREEREFERRER993(address _token, address _user) public view returns(address) { //inject NONSTANDARD NAMING
if(users[_user].referral[_token].length < REFERRER_1_LEVEL_LIMIT) return _user;
address[] memory referrals = new address[](315);
referrals[0] = users[_user].referral[_token][0];
referrals[1] = users[_user].referral[_token][1];
referrals[2] = users[_user].referral[_token][2];
referrals[3] = users[_user].referral[_token][3];
referrals[4] = users[_user].referral[_token][4];
address freeReferrer;
bool noFreeReferrer = true;
for(uint i = 0; i < 126; i++) {
if(users[referrals[i]].referral[_token].length == REFERRER_1_LEVEL_LIMIT) {
if(i < 155) {
referrals[(i+1)*2] = users[referrals[i]].referral[_token][0];
referrals[(i+1)*2+1] = users[referrals[i]].referral[_token][2];
referrals[(i+1)*2+2] = users[referrals[i]].referral[_token][3];
referrals[(i+1)*2+3] = users[referrals[i]].referral[_token][4];
referrals[(i+1)*2+4] = users[referrals[i]].referral[_token][5];
}
}
else {
noFreeReferrer = false;
freeReferrer = referrals[i];
break;
}
}
require(!noFreeReferrer, 'No Free Referrer');
return freeReferrer;
}
function WITHDRAW913(address _token) public { //inject NONSTANDARD NAMING
uint256 total = users[msg.sender].tokenRewards[_token];
require(total > 0, "Nothing to withdraw");
users[msg.sender].tokenRewards[_token] = 0;
IERC20 token = IERC20(_token);
require(token.TRANSFER190(msg.sender, total), "Couldn't send the tokens");
}
function _WITHDRAWFEES891(address _token) public ONLYOWNER423 { //inject NONSTANDARD NAMING
uint256 total = ownerFees[_token];
require(total > 0, "Nothing to withdraw");
ownerFees[_token] = 0;
IERC20 token = IERC20(_token);
require(token.TRANSFER190(msg.sender, total), "Couldn't send the tokens");
}
function VIEWUSERREFERRAL790(address _token, address _user) public view returns(address[] memory) { //inject NONSTANDARD NAMING
return users[_user].referral[_token];
}
function VIEWUSERREFERRER85(address _token, address _user) public view returns(uint256) { //inject NONSTANDARD NAMING
return users[_user].referrerID[_token];
}
function VIEWUSERLEVELEXPIRED566(address _token, address _user, uint _level) public view returns(uint) { //inject NONSTANDARD NAMING
return users[_user].levelExpired[_token][_level];
}
function VIEWUSERISEXIST611(address _user) public view returns(bool) { //inject NONSTANDARD NAMING
return users[_user].isExist;
}
function VIEWUSERREWARDS680(address _user, address _token) public view returns(uint256) { //inject NONSTANDARD NAMING
return users[_user].tokenRewards[_token];
}
function BYTESTOADDRESS886(bytes memory bys) private pure returns (address addr) { //inject NONSTANDARD NAMING
assembly {
addr := mload(add(bys, 20))
}
}
function _CLOSE871(address payable _to) public ONLYOWNER423 { //inject NONSTANDARD NAMING
selfdestruct(_to);
}
}
|
inject NONSTANDARD NAMING
|
function SETADMINFEEPERCENTAGE408(uint _adminFeePercentage) public ONLYOWNER423 {
| 15,849,265
|
pragma solidity ^0.8;
contract StartStopUpdateExample {
address public owner;
bool public paused;
//Just like classes, a constructor automatically assigns variables (does something) when contract is called
constructor() public {
//owner is address/person who deploys contract
owner = msg.sender;
}
function sendMoney() payable public {
}
//owner can pause contract so it won't execute
function setPaused() public {
require(owner == msg.sender, "oh my gah you're not the owner >:(");
paused = !paused;
}
//transfers all money in smart contract to givenaddress
function withdrawMoney(address payable _to) public {
//In solidity, require is the equivalent to if statements (conditionals) for the code to continue in the function
//param1 is the thing that needs to be true, param2 is the error or exception and the error message
//owner must be the address withdrawing money so they're in control
require(msg.sender == owner, "You're not the owner");
require(!paused, "Soz contract is paused");
_to.transfer(address(this).balance);
}
function destroySmartContract(address payable _to) public {
//This function destroys the deployed Smart contract. But, the parameter is an address which will receive the remaining balance in the smart contract
//so it's basically not wasted. Once this code runs:
/**
"You can still send transactions to the address and transfer Ether there, but there won't be any code that could send you the Ether back."
*/
require(msg.sender == owner, "You are not the owner");
selfdestruct(_to);
}
}
/**
For contracts to undergo transactions, an external account (one with a private key) needs to initiate it.
It is the blockchain (ledger or database) that stores information about each address (balance and transfer), but each address stores a private key. So money is not
inside the wallet, just the blockchain.
.send() returns a boolean (true if transaction succeeded, false if it didn't go through or there's an exception)
IMPORTANT GLOBAL PROPERTIES
msg.sender - address of person who called the function or deployed contract
msg.value - amount of ETH the contract received
now - current timestamp (plus or minus 15 seconds because of miners so not extremely accurate)
A function receives ETH if it is "payable". Keyword must be used in code.
to.transfer(address(this).balance)
the "to" is the address the money is going to
the address(this).balance is the amount of money being transferred from smart contract to "to"
*/
|
This function destroys the deployed Smart contract. But, the parameter is an address which will receive the remaining balance in the smart contractso it's basically not wasted. Once this code runs:
|
function destroySmartContract(address payable _to) public {
"You can still send transactions to the address and transfer Ether there, but there won't be any code that could send you the Ether back."
require(msg.sender == owner, "You are not the owner");
selfdestruct(_to);
| 12,755,371
|
./full_match/83/0x41eB86d3FF7a5b039a2f16CFB5CA469cA130aaab/sources/contracts/CToken/CToken.sol
|
Reduces reserves by transferring to admin Requires fresh interest accrual reduceAmount Amount of reduction to reserves return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ totalReserves - reduceAmount We fail gracefully unless market's block number equals current block number Fail gracefully if protocol has insufficient underlying cash Check reduceAmount ≤ reserves[n] (totalReserves)
|
function _reduceReservesFresh(uint256 reduceAmount) internal onlyAdmin returns (uint256) {
uint256 totalReservesNew;
if (accrualBlockNumber != getBlockNumber()) {
Error.MARKET_NOT_FRESH.fail(FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
if (getCashPrior() < reduceAmount) {
Error.TOKEN_INSUFFICIENT_CASH.fail(FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
if (reduceAmount > totalReserves) {
Error.BAD_INPUT.fail(FailureInfo.REDUCE_RESERVES_VALIDATION);
}
totalReservesNew = totalReserves - reduceAmount;
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint256(Error.NO_ERROR);
}
| 9,557,200
|
./partial_match/1/0x809416858a4d0cAA83a660C54B59c4180C6d1Be3/sources/UController.sol
|
externalTokenApproval approve the spender address to spend a specified amount of tokens on behalf of msg.sender. _externalToken the address of the Token Contract _spender address _value the amount of ether (in Wei) which the approval is referring to. return bool which represents a success/
|
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
onlyRegisteredScheme(address(_avatar))
onlySubjectToConstraint("externalTokenApproval", address(_avatar))
returns(bool)
{
return _avatar.externalTokenApproval(_externalToken, _spender, _value);
}
| 16,037,368
|
//Address: 0x00416B9d728069eDB0cEb04bC2b203fA7336d1F1
//Contract name: AversafeSeedCrowdsale
//Balance: 0 Ether
//Verification Date: 11/29/2017
//Transacion Count: 36
// CODE STARTS HERE
/*
Copyright 2017 Cofound.it.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.13;
contract ReentrancyHandlingContract {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
}
contract Owned {
address public owner;
address public newOwner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract PriorityPassInterface {
function getAccountLimit(address _accountAddress) public constant returns (uint);
function getAccountActivity(address _accountAddress) public constant returns (bool);
}
contract ERC20TokenInterface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract SeedCrowdsaleContract is ReentrancyHandlingContract, Owned {
struct ContributorData {
uint contributionAmount;
}
mapping(address => ContributorData) public contributorList;
uint public nextContributorIndex;
mapping(uint => address) public contributorIndexes;
state public crowdsaleState = state.pendingStart;
enum state { pendingStart, priorityPass, openedPriorityPass, crowdsaleEnded }
uint public presaleStartTime;
uint public presaleUnlimitedStartTime;
uint public crowdsaleEndedTime;
event PresaleStarted(uint blocktime);
event PresaleUnlimitedStarted(uint blocktime);
event CrowdsaleEnded(uint blocktime);
event ErrorSendingETH(address to, uint amount);
event MinCapReached(uint blocktime);
event MaxCapReached(uint blocktime);
event ContributionMade(address indexed contributor, uint amount);
PriorityPassInterface priorityPassContract = PriorityPassInterface(0x0);
uint public minCap;
uint public maxP1Cap;
uint public maxCap;
uint public ethRaised;
address public multisigAddress;
uint nextContributorToClaim;
mapping(address => bool) hasClaimedEthWhenFail;
//
// Unnamed function that runs when eth is sent to the contract
// @payable
//
function() noReentrancy payable public {
require(msg.value != 0); // Throw if value is 0
require(crowdsaleState != state.crowdsaleEnded); // Check if crowdsale has ended
bool stateChanged = checkCrowdsaleState(); // Check blocks time and calibrate crowdsale state
if (crowdsaleState == state.priorityPass) {
if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass
processTransaction(msg.sender, msg.value); // Process transaction and issue tokens
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
} else if (crowdsaleState == state.openedPriorityPass) {
if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass
processTransaction(msg.sender, msg.value); // Process transaction and issue tokens
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
}
//
// @internal checks crowdsale state and emits events it
// @returns boolean
//
function checkCrowdsaleState() internal returns (bool) {
if (ethRaised == maxCap && crowdsaleState != state.crowdsaleEnded) { // Check if max cap is reached
crowdsaleState = state.crowdsaleEnded;
MaxCapReached(block.timestamp); // Close the crowdsale
CrowdsaleEnded(block.timestamp); // Raise event
return true;
}
if (block.timestamp > presaleStartTime && block.timestamp <= presaleUnlimitedStartTime) { // Check if we are in presale phase
if (crowdsaleState != state.priorityPass) { // Check if state needs to be changed
crowdsaleState = state.priorityPass; // Set new state
PresaleStarted(block.timestamp); // Raise event
return true;
}
} else if (block.timestamp > presaleUnlimitedStartTime && block.timestamp <= crowdsaleEndedTime) { // Check if we are in presale unlimited phase
if (crowdsaleState != state.openedPriorityPass) { // Check if state needs to be changed
crowdsaleState = state.openedPriorityPass; // Set new state
PresaleUnlimitedStarted(block.timestamp); // Raise event
return true;
}
} else {
if (crowdsaleState != state.crowdsaleEnded && block.timestamp > crowdsaleEndedTime) {// Check if crowdsale is over
crowdsaleState = state.crowdsaleEnded; // Set new state
CrowdsaleEnded(block.timestamp); // Raise event
return true;
}
}
return false;
}
//
// @internal determines if return eth or throw according to changing state
// @param _stateChanged boolean message about state change
//
function refundTransaction(bool _stateChanged) internal {
if (_stateChanged) {
msg.sender.transfer(msg.value);
} else {
revert();
}
}
//
// Getter to calculate how much user can contribute
// @param _contributor address of the contributor
//
function calculateMaxContribution(address _contributor) constant public returns (uint maxContribution) {
uint maxContrib;
if (crowdsaleState == state.priorityPass) { // Check if we are in priority pass
maxContrib = priorityPassContract.getAccountLimit(_contributor) - contributorList[_contributor].contributionAmount;
if (maxContrib > (maxP1Cap - ethRaised)) { // Check if max contribution is more that max cap
maxContrib = maxP1Cap - ethRaised; // Alter max cap
}
} else {
maxContrib = maxCap - ethRaised; // Alter max cap
}
return maxContrib;
}
//
// Return if there is overflow of contributed eth
// @internal processes transactions
// @param _contributor address of an contributor
// @param _amount contributed amount
//
function processTransaction(address _contributor, uint _amount) internal {
uint maxContribution = calculateMaxContribution(_contributor); // Calculate max users contribution
uint contributionAmount = _amount;
uint returnAmount = 0;
if (maxContribution < _amount) { // Check if max contribution is lower than _amount sent
contributionAmount = maxContribution; // Set that user contributes his maximum alowed contribution
returnAmount = _amount - maxContribution; // Calculate how much he must get back
}
if (ethRaised + contributionAmount >= minCap && minCap > ethRaised) {
MinCapReached(block.timestamp);
}
if (contributorList[_contributor].contributionAmount == 0) { // Check if contributor has already contributed
contributorList[_contributor].contributionAmount = contributionAmount; // Set their contribution
contributorIndexes[nextContributorIndex] = _contributor; // Set contributors index
nextContributorIndex++;
} else {
contributorList[_contributor].contributionAmount += contributionAmount; // Add contribution amount to existing contributor
}
ethRaised += contributionAmount; // Add to eth raised
ContributionMade(msg.sender, contributionAmount); // Raise event about contribution
if (returnAmount != 0) {
_contributor.transfer(returnAmount); // Return overflow of ether
}
}
//
// Recovers ERC20 tokens other than eth that are send to this address
// @owner refunds the erc20 tokens
// @param _tokenAddress address of the erc20 token
// @param _to address to where tokens should be send to
// @param _amount amount of tokens to refund
//
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public {
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
//
// withdrawEth when minimum cap is reached
// @owner sets contributions to withdraw
//
function withdrawEth() onlyOwner public {
require(this.balance != 0);
require(ethRaised >= minCap);
pendingEthWithdrawal = this.balance;
}
uint public pendingEthWithdrawal;
//
// pulls the funds that were set to send with calling of
// withdrawEth when minimum cap is reached
// @multisig pulls the contributions to self
//
function pullBalance() public {
require(msg.sender == multisigAddress);
require(pendingEthWithdrawal > 0);
multisigAddress.transfer(pendingEthWithdrawal);
pendingEthWithdrawal = 0;
}
//
// Owner can batch return contributors contributions(eth)
// @owner returns contributions
// @param _numberOfReturns number of returns to do in one transaction
//
function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public {
require(block.timestamp > crowdsaleEndedTime && ethRaised < minCap); // Check if crowdsale has failed
address currentParticipantAddress;
uint contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {
currentParticipantAddress = contributorIndexes[nextContributorToClaim]; // Get next unclaimed participant
if (currentParticipantAddress == 0x0) {
return; // Check if all the participants were compensated
}
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if participant has already claimed
contribution = contributorList[currentParticipantAddress].contributionAmount; // Get contribution of participant
hasClaimedEthWhenFail[currentParticipantAddress] = true; // Set that he has claimed
if (!currentParticipantAddress.send(contribution)) { // Refund eth
ErrorSendingETH(currentParticipantAddress, contribution); // If there is an issue raise event for manual recovery
}
}
nextContributorToClaim += 1; // Repeat
}
}
//
// If there were any issue with refund owner can withdraw eth at the end for manual recovery
// @owner withdraws remaining funds
//
function withdrawRemainingBalanceForManualRecovery() onlyOwner public {
require(this.balance != 0); // Check if there are any eth to claim
require(block.timestamp > crowdsaleEndedTime); // Check if crowdsale is over
require(contributorIndexes[nextContributorToClaim] == 0x0); // Check if all the users were refunded
multisigAddress.transfer(this.balance); // Withdraw to multisig for manual processing
}
//
// Owner can set multisig address for crowdsale
// @owner sets an address where funds will go
// @param _newAddress
//
function setMultisigAddress(address _newAddress) onlyOwner public {
multisigAddress = _newAddress;
}
//
// Setter for the whitelist contract
// @owner sets address of whitelist contract
// @param address
//
function setPriorityPassContract(address _newAddress) onlyOwner public {
priorityPassContract = PriorityPassInterface(_newAddress);
}
//
// Getter for the whitelist contract
// @returns white list contract address
//
function priorityPassContractAddress() constant public returns (address) {
return address(priorityPassContract);
}
//
// Before crowdsale starts owner can calibrate time of crowdsale stages
// @owner sends new times for the sale
// @param _presaleStartTime timestamp for sale limited start
// @param _presaleUnlimitedStartTime timestamp for sale unlimited
// @param _crowdsaleEndedTime timestamp for ending sale
//
function setCrowdsaleTimes(uint _presaleStartTime, uint _presaleUnlimitedStartTime, uint _crowdsaleEndedTime) onlyOwner public {
require(crowdsaleState == state.pendingStart); // Check if crowdsale has started
require(_presaleStartTime != 0); // Check if any value is 0
require(_presaleStartTime < _presaleUnlimitedStartTime); // Check if presaleUnlimitedStartTime is set properly
require(_presaleUnlimitedStartTime != 0); // Check if any value is 0
require(_presaleUnlimitedStartTime < _crowdsaleEndedTime); // Check if crowdsaleEndedTime is set properly
require(_crowdsaleEndedTime != 0); // Check if any value is 0
presaleStartTime = _presaleStartTime;
presaleUnlimitedStartTime = _presaleUnlimitedStartTime;
crowdsaleEndedTime = _crowdsaleEndedTime;
}
}
contract AversafeSeedCrowdsale is SeedCrowdsaleContract {
function AversafeSeedCrowdsale() {
presaleStartTime = 1512032400;
presaleUnlimitedStartTime = 1512063000;
crowdsaleEndedTime = 1512140400;
minCap = 451 ether;
maxP1Cap = 802 ether;
maxCap = 891 ether;
}
}
|
If there were any issue with refund owner can withdraw eth at the end for manual recovery @owner withdraws remaining funds
|
function withdrawRemainingBalanceForManualRecovery() onlyOwner public {
}
| 1,003,056
|
./full_match/1/0x07B3DD2B07613eF877cF6392a971D00E36Fe2Ee2/sources/contracts/ForgeV1.sol
|
withdrawal fee calculation based on contribution time 0-30 days 5% 31-60 days 4% 61 - 90 days 2.5% above 91 days 0%
|
function capitalSlash(uint256 amount, uint256 contributionTime) public view returns (uint256) {
uint256 currentTime = block.timestamp;
if ((contributionTime <= currentTime)
&& (currentTime < contributionTime + WITHDRAW_FEE_5_PERCENT_PERIOD)) {
return amount * (WITHDRAW_FEE_FACTOR - WITHDRAW_FEE_5_PERCENT) / WITHDRAW_FEE_FACTOR;
}
if ((contributionTime + WITHDRAW_FEE_5_PERCENT_PERIOD <= currentTime)
&& (currentTime < contributionTime + WITHDRAW_FEE_4_PERCENT_PERIOD)) {
return amount * (WITHDRAW_FEE_FACTOR - WITHDRAW_FEE_4_PERCENT) / WITHDRAW_FEE_FACTOR;
}
if ((contributionTime + WITHDRAW_FEE_4_PERCENT_PERIOD <= currentTime)
&& (currentTime < contributionTime + WITHDRAW_FEE_2_5_PERCENT_PERIOD)) {
return amount * (WITHDRAW_FEE_FACTOR - WITHDRAW_FEE_2_5_PERCENT) / WITHDRAW_FEE_FACTOR;
}
return amount;
}
| 16,609,192
|
//Address: 0x9fa8fa61a10ff892e4ebceb7f4e0fc684c2ce0a9
//Contract name: HONG
//Balance: 1,003.624048369852000001 Ether
//Verification Date: 6/13/2017
//Transacion Count: 229
// CODE STARTS HERE
/* Verified by 3esmit
- Bytecode Verification performed was compared on second iteration -
This file is part of the HONG.
The HONG is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The HONG 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 lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with the HONG. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Parent contract that contains all of the configurable parameters of the main contract.
*/
contract HongConfiguration {
uint public closingTime;
uint public weiPerInitialHONG = 10**16;
string public name = "HONG";
string public symbol = "Ħ";
uint8 public decimals = 0;
uint public maxBountyTokens = 2 * (10**6);
uint public closingTimeExtensionPeriod = 30 days;
uint public minTokensToCreate = 100 * (10**6);
uint public maxTokensToCreate = 250 * (10**6);
uint public tokensPerTier = 50 * (10**6);
uint public lastKickoffDateBuffer = 304 days;
uint public mgmtRewardPercentage = 20;
uint public mgmtFeePercentage = 8;
uint public harvestQuorumPercent = 20;
uint public freezeQuorumPercent = 50;
uint public kickoffQuorumPercent = 20;
}
contract ErrorHandler {
bool public isInTestMode = false;
event evRecord(address msg_sender, uint msg_value, string message);
function doThrow(string message) internal {
evRecord(msg.sender, msg.value, message);
if(!isInTestMode){
throw;
}
}
}
contract TokenInterface is ErrorHandler {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public tokensCreated;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _amount) returns (bool success);
event evTransfer(address msg_sender, uint msg_value, address indexed _from, address indexed _to, uint256 _amount);
// Modifier that allows only token holders to trigger
modifier onlyTokenHolders {
if (balanceOf(msg.sender) == 0) doThrow("onlyTokenHolders"); else {_}
}
}
contract Token is TokenInterface {
// Protects users by preventing the execution of method calls that
// inadvertently also transferred ether
modifier noEther() {if (msg.value > 0) doThrow("noEther"); else{_}}
modifier hasEther() {if (msg.value <= 0) doThrow("hasEther"); else{_}}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) noEther returns (bool success) {
if (_amount <= 0) return false;
if (balances[msg.sender] < _amount) return false;
if (balances[_to] + _amount < balances[_to]) return false;
balances[msg.sender] -= _amount;
balances[_to] += _amount;
evTransfer(msg.sender, msg.value, msg.sender, _to, _amount);
return true;
}
}
contract OwnedAccount is ErrorHandler {
address public owner;
bool acceptDeposits = true;
event evPayOut(address msg_sender, uint msg_value, address indexed _recipient, uint _amount);
modifier onlyOwner() {
if (msg.sender != owner) doThrow("onlyOwner");
else {_}
}
modifier noEther() {
if (msg.value > 0) doThrow("noEther");
else {_}
}
function OwnedAccount(address _owner) {
owner = _owner;
}
function payOutPercentage(address _recipient, uint _percent) internal onlyOwner noEther {
payOutAmount(_recipient, (this.balance * _percent) / 100);
}
function payOutAmount(address _recipient, uint _amount) internal onlyOwner noEther {
// send does not forward enough gas to see that this is a managed account call
if (!_recipient.call.value(_amount)())
doThrow("payOut:sendFailed");
else
evPayOut(msg.sender, msg.value, _recipient, _amount);
}
function () returns (bool success) {
if (!acceptDeposits) throw;
return true;
}
}
contract ReturnWallet is OwnedAccount {
address public mgmtBodyWalletAddress;
bool public inDistributionMode;
uint public amountToDistribute;
uint public totalTokens;
uint public weiPerToken;
function ReturnWallet(address _mgmtBodyWalletAddress) OwnedAccount(msg.sender) {
mgmtBodyWalletAddress = _mgmtBodyWalletAddress;
}
function payManagementBodyPercent(uint _percent) {
payOutPercentage(mgmtBodyWalletAddress, _percent);
}
function switchToDistributionMode(uint _totalTokens) onlyOwner {
inDistributionMode = true;
acceptDeposits = false;
totalTokens = _totalTokens;
amountToDistribute = this.balance;
weiPerToken = amountToDistribute / totalTokens;
}
function payTokenHolderBasedOnTokenCount(address _tokenHolderAddress, uint _tokens) onlyOwner {
payOutAmount(_tokenHolderAddress, weiPerToken * _tokens);
}
}
contract ExtraBalanceWallet is OwnedAccount {
address returnWalletAddress;
function ExtraBalanceWallet(address _returnWalletAddress) OwnedAccount(msg.sender) {
returnWalletAddress = _returnWalletAddress;
}
function returnBalanceToMainAccount() {
acceptDeposits = false;
payOutAmount(owner, this.balance);
}
function returnAmountToMainAccount(uint _amount) {
payOutAmount(owner, _amount);
}
function payBalanceToReturnWallet() {
acceptDeposits = false;
payOutAmount(returnWalletAddress, this.balance);
}
}
contract RewardWallet is OwnedAccount {
address public returnWalletAddress;
function RewardWallet(address _returnWalletAddress) OwnedAccount(msg.sender) {
returnWalletAddress = _returnWalletAddress;
}
function payBalanceToReturnWallet() {
acceptDeposits = false;
payOutAmount(returnWalletAddress, this.balance);
}
}
contract ManagementFeeWallet is OwnedAccount {
address public mgmtBodyAddress;
address public returnWalletAddress;
function ManagementFeeWallet(address _mgmtBodyAddress, address _returnWalletAddress) OwnedAccount(msg.sender) {
mgmtBodyAddress = _mgmtBodyAddress;
returnWalletAddress = _returnWalletAddress;
}
function payManagementBodyAmount(uint _amount) {
payOutAmount(mgmtBodyAddress, _amount);
}
function payBalanceToReturnWallet() {
acceptDeposits = false;
payOutAmount(returnWalletAddress, this.balance);
}
}
/*
* Token Creation contract, similar to other organization,for issuing tokens and initialize
* its ether fund.
*/
contract TokenCreationInterface is HongConfiguration {
address public managementBodyAddress;
ExtraBalanceWallet public extraBalanceWallet;
mapping (address => uint256) weiGiven;
mapping (address => uint256) public taxPaid;
function createTokenProxy(address _tokenHolder) internal returns (bool success);
function refundMyIcoInvestment();
function divisor() constant returns (uint divisor);
event evMinTokensReached(address msg_sender, uint msg_value, uint value);
event evCreatedToken(address msg_sender, uint msg_value, address indexed to, uint amount);
event evRefund(address msg_sender, uint msg_value, address indexed to, uint value, bool result);
}
contract GovernanceInterface is ErrorHandler, HongConfiguration {
// The variable indicating whether the fund has achieved the inital goal or not.
// This value is automatically set, and CANNOT be reversed.
bool public isFundLocked;
bool public isFundReleased;
modifier notLocked() {if (isFundLocked) doThrow("notLocked"); else {_}}
modifier onlyLocked() {if (!isFundLocked) doThrow("onlyLocked"); else {_}}
modifier notReleased() {if (isFundReleased) doThrow("notReleased"); else {_}}
modifier onlyHarvestEnabled() {if (!isHarvestEnabled) doThrow("onlyHarvestEnabled"); else {_}}
modifier onlyDistributionNotInProgress() {if (isDistributionInProgress) doThrow("onlyDistributionNotInProgress"); else {_}}
modifier onlyDistributionNotReady() {if (isDistributionReady) doThrow("onlyDistributionNotReady"); else {_}}
modifier onlyDistributionReady() {if (!isDistributionReady) doThrow("onlyDistributionReady"); else {_}}
modifier onlyCanIssueBountyToken(uint _amount) {
if (bountyTokensCreated + _amount > maxBountyTokens){
doThrow("hitMaxBounty");
}
else {_}
}
modifier onlyFinalFiscalYear() {
// Only call harvest() in the final fiscal year
if (currentFiscalYear < 4) doThrow("currentFiscalYear<4"); else {_}
}
modifier notFinalFiscalYear() {
// Token holders cannot freeze fund at the 4th Fiscal Year after passing `kickoff(4)` voting
if (currentFiscalYear >= 4) doThrow("currentFiscalYear>=4"); else {_}
}
modifier onlyNotFrozen() {
if (isFreezeEnabled) doThrow("onlyNotFrozen"); else {_}
}
bool public isDayThirtyChecked;
bool public isDaySixtyChecked;
uint256 public bountyTokensCreated;
uint public currentFiscalYear;
uint public lastKickoffDate;
mapping (uint => bool) public isKickoffEnabled;
bool public isFreezeEnabled;
bool public isHarvestEnabled;
bool public isDistributionInProgress;
bool public isDistributionReady;
ReturnWallet public returnWallet;
RewardWallet public rewardWallet;
ManagementFeeWallet public managementFeeWallet;
// define the governance of this organization and critical functions
function mgmtIssueBountyToken(address _recipientAddress, uint _amount) returns (bool);
function mgmtDistribute();
function mgmtInvestProject(
address _projectWallet,
uint _amount
) returns (bool);
event evIssueManagementFee(address msg_sender, uint msg_value, uint _amount, bool _success);
event evMgmtIssueBountyToken(address msg_sender, uint msg_value, address _recipientAddress, uint _amount, bool _success);
event evMgmtDistributed(address msg_sender, uint msg_value, uint256 _amount, bool _success);
event evMgmtInvestProject(address msg_sender, uint msg_value, address _projectWallet, uint _amount, bool result);
event evLockFund(address msg_sender, uint msg_value);
event evReleaseFund(address msg_sender, uint msg_value);
}
contract TokenCreation is TokenCreationInterface, Token, GovernanceInterface {
modifier onlyManagementBody {
if(msg.sender != address(managementBodyAddress)) {doThrow("onlyManagementBody");} else {_}
}
function TokenCreation(
address _managementBodyAddress,
uint _closingTime) {
managementBodyAddress = _managementBodyAddress;
closingTime = _closingTime;
}
function createTokenProxy(address _tokenHolder) internal notLocked notReleased hasEther returns (bool success) {
// Business logic (but no state changes)
// setup transaction details
uint tokensSupplied = 0;
uint weiAccepted = 0;
bool wasMinTokensReached = isMinTokensReached();
var weiPerLatestHONG = weiPerInitialHONG * divisor() / 100;
uint remainingWei = msg.value;
uint tokensAvailable = tokensAvailableAtCurrentTier();
if (tokensAvailable == 0) {
doThrow("noTokensToSell");
return false;
}
// Sell tokens in batches based on the current price.
while (remainingWei >= weiPerLatestHONG) {
uint tokensRequested = remainingWei / weiPerLatestHONG;
uint tokensToSellInBatch = min(tokensAvailable, tokensRequested);
// special case. Allow the last purchase to go over the max
if (tokensAvailable == 0 && tokensCreated == maxTokensToCreate) {
tokensToSellInBatch = tokensRequested;
}
uint priceForBatch = tokensToSellInBatch * weiPerLatestHONG;
// track to total wei accepted and total tokens supplied
weiAccepted += priceForBatch;
tokensSupplied += tokensToSellInBatch;
// update state
balances[_tokenHolder] += tokensToSellInBatch;
tokensCreated += tokensToSellInBatch;
weiGiven[_tokenHolder] += priceForBatch;
// update dependent values (state has changed)
weiPerLatestHONG = weiPerInitialHONG * divisor() / 100;
remainingWei = msg.value - weiAccepted;
tokensAvailable = tokensAvailableAtCurrentTier();
}
// the caller will still pay this amount, even though it didn't buy any tokens.
weiGiven[_tokenHolder] += remainingWei;
// when the caller is paying more than 10**16 wei (0.01 Ether) per token, the extra is basically a tax.
uint256 totalTaxLevied = weiAccepted - tokensSupplied * weiPerInitialHONG;
taxPaid[_tokenHolder] += totalTaxLevied;
// State Changes (no external calls)
tryToLockFund();
// External calls
if (totalTaxLevied > 0) {
if (!extraBalanceWallet.send(totalTaxLevied)){
doThrow("extraBalance:sendFail");
return;
}
}
// Events. Safe to publish these now that we know it all worked
evCreatedToken(msg.sender, msg.value, _tokenHolder, tokensSupplied);
if (!wasMinTokensReached && isMinTokensReached()) evMinTokensReached(msg.sender, msg.value, tokensCreated);
if (isFundLocked) evLockFund(msg.sender, msg.value);
if (isFundReleased) evReleaseFund(msg.sender, msg.value);
return true;
}
function refundMyIcoInvestment() noEther notLocked onlyTokenHolders {
// 1: Preconditions
if (weiGiven[msg.sender] == 0) {
doThrow("noWeiGiven");
return;
}
if (balances[msg.sender] > tokensCreated) {
doThrow("invalidTokenCount");
return;
}
// 2: Business logic
bool wasMinTokensReached = isMinTokensReached();
var tmpWeiGiven = weiGiven[msg.sender];
var tmpTaxPaidBySender = taxPaid[msg.sender];
var tmpSenderBalance = balances[msg.sender];
var amountToRefund = tmpWeiGiven;
// 3: state changes.
balances[msg.sender] = 0;
weiGiven[msg.sender] = 0;
taxPaid[msg.sender] = 0;
tokensCreated -= tmpSenderBalance;
// 4: external calls
// Pull taxes paid back into this contract (they would have been paid into the extraBalance account)
extraBalanceWallet.returnAmountToMainAccount(tmpTaxPaidBySender);
// If that works, then do a refund
if (!msg.sender.send(amountToRefund)) {
evRefund(msg.sender, msg.value, msg.sender, amountToRefund, false);
doThrow("refund:SendFailed");
return;
}
evRefund(msg.sender, msg.value, msg.sender, amountToRefund, true);
if (!wasMinTokensReached && isMinTokensReached()) evMinTokensReached(msg.sender, msg.value, tokensCreated);
}
// Using a function rather than a state variable, as it reduces the risk of inconsistent state
function isMinTokensReached() constant returns (bool) {
return tokensCreated >= minTokensToCreate;
}
function isMaxTokensReached() constant returns (bool) {
return tokensCreated >= maxTokensToCreate;
}
function mgmtIssueBountyToken(
address _recipientAddress,
uint _amount
) noEther onlyManagementBody onlyCanIssueBountyToken(_amount) returns (bool){
// send token to the specified address
balances[_recipientAddress] += _amount;
bountyTokensCreated += _amount;
// event
evMgmtIssueBountyToken(msg.sender, msg.value, _recipientAddress, _amount, true);
}
function mgmtDistribute() onlyManagementBody hasEther onlyHarvestEnabled onlyDistributionNotReady {
distributeDownstream(mgmtRewardPercentage);
}
function distributeDownstream(uint _mgmtPercentage) internal onlyDistributionNotInProgress {
// transfer all balance from the following accounts
// (1) HONG main account,
// (2) managementFeeWallet,
// (3) rewardWallet
// (4) extraBalanceWallet
// to returnWallet
// And allocate _mgmtPercentage of the fund to ManagementBody
// State changes first (even though it feels backwards)
isDistributionInProgress = true;
isDistributionReady = true;
payBalanceToReturnWallet();
managementFeeWallet.payBalanceToReturnWallet();
rewardWallet.payBalanceToReturnWallet();
extraBalanceWallet.payBalanceToReturnWallet();
// transfer _mgmtPercentage of returns to mgmt Wallet
if (_mgmtPercentage > 0) returnWallet.payManagementBodyPercent(_mgmtPercentage);
returnWallet.switchToDistributionMode(tokensCreated + bountyTokensCreated);
// Token holder can claim the remaining fund (the total amount harvested/ to be distributed) starting from here
evMgmtDistributed(msg.sender, msg.value, returnWallet.balance, true);
isDistributionInProgress = false;
}
function payBalanceToReturnWallet() internal {
if (!returnWallet.send(this.balance))
doThrow("payBalanceToReturnWallet:sendFailed");
return;
}
function min(uint a, uint b) constant internal returns (uint) {
return (a < b) ? a : b;
}
function tryToLockFund() internal {
// ICO Diagram: https://github.com/hongcoin/DO/wiki/ICO-Period-and-Target
if (isFundReleased) {
// Do not change the state anymore
return;
}
// Case A
isFundLocked = isMaxTokensReached();
// if we've reached the 30 day mark, try to lock the fund
if (!isFundLocked && !isDayThirtyChecked && (now >= closingTime)) {
if (isMinTokensReached()) {
// Case B
isFundLocked = true;
}
isDayThirtyChecked = true;
}
// if we've reached the 60 day mark, try to lock the fund
if (!isFundLocked && !isDaySixtyChecked && (now >= (closingTime + closingTimeExtensionPeriod))) {
if (isMinTokensReached()) {
// Case C
isFundLocked = true;
}
isDaySixtyChecked = true;
}
if (isDaySixtyChecked && !isMinTokensReached()) {
// Case D
// Mark the release state. No fund should be accepted anymore
isFundReleased = true;
}
}
function tokensAvailableAtTierInternal(uint8 _currentTier, uint _tokensPerTier, uint _tokensCreated) constant returns (uint) {
uint tierThreshold = (_currentTier+1) * _tokensPerTier;
// never go above maxTokensToCreate, which could happen if the max is not a multiple of _tokensPerTier
if (tierThreshold > maxTokensToCreate) {
tierThreshold = maxTokensToCreate;
}
// this can happen on the final purchase in the last tier
if (_tokensCreated > tierThreshold) {
return 0;
}
return tierThreshold - _tokensCreated;
}
function tokensAvailableAtCurrentTier() constant returns (uint) {
return tokensAvailableAtTierInternal(getCurrentTier(), tokensPerTier, tokensCreated);
}
function getCurrentTier() constant returns (uint8) {
uint8 tier = (uint8) (tokensCreated / tokensPerTier);
return (tier > 4) ? 4 : tier;
}
function pricePerTokenAtCurrentTier() constant returns (uint) {
return weiPerInitialHONG * divisor() / 100;
}
function divisor() constant returns (uint divisor) {
// Quantity divisor model: based on total quantity of coins issued
// Price ranged from 1.0 to 1.20 Ether for all HONG Tokens with a 0.05 ETH increase for each tier
// The number of (base unit) tokens per wei is calculated
// as `msg.value` * 100 / `divisor`
return 100 + getCurrentTier() * 5;
}
}
contract HONGInterface is ErrorHandler, HongConfiguration {
// we do not have grace period. Once the goal is reached, the fund is secured
address public managementBodyAddress;
// 3 most important votings in blockchain
mapping (uint => mapping (address => uint)) public votedKickoff;
mapping (address => uint) public votedFreeze;
mapping (address => uint) public votedHarvest;
mapping (uint => uint256) public supportKickoffQuorum;
uint256 public supportFreezeQuorum;
uint256 public supportHarvestQuorum;
uint public totalInitialBalance;
uint public annualManagementFee;
function voteToKickoffNewFiscalYear();
function voteToFreezeFund();
function recallVoteToFreezeFund();
function voteToHarvestFund();
function collectMyReturn();
// Trigger the following events when the voting result is available
event evKickoff(address msg_sender, uint msg_value, uint _fiscal);
event evFreeze(address msg_sender, uint msg_value);
event evHarvest(address msg_sender, uint msg_value);
}
// The HONG contract itself
contract HONG is HONGInterface, Token, TokenCreation {
function HONG(
address _managementBodyAddress,
uint _closingTime,
uint _closingTimeExtensionPeriod,
uint _lastKickoffDateBuffer,
uint _minTokensToCreate,
uint _maxTokensToCreate,
uint _tokensPerTier,
bool _isInTestMode
) TokenCreation(_managementBodyAddress, _closingTime) {
managementBodyAddress = _managementBodyAddress;
closingTimeExtensionPeriod = _closingTimeExtensionPeriod;
lastKickoffDateBuffer = _lastKickoffDateBuffer;
minTokensToCreate = _minTokensToCreate;
maxTokensToCreate = _maxTokensToCreate;
tokensPerTier = _tokensPerTier;
isInTestMode = _isInTestMode;
returnWallet = new ReturnWallet(managementBodyAddress);
rewardWallet = new RewardWallet(address(returnWallet));
managementFeeWallet = new ManagementFeeWallet(managementBodyAddress, address(returnWallet));
extraBalanceWallet = new ExtraBalanceWallet(address(returnWallet));
if (address(extraBalanceWallet) == 0)
doThrow("extraBalanceWallet:0");
if (address(returnWallet) == 0)
doThrow("returnWallet:0");
if (address(rewardWallet) == 0)
doThrow("rewardWallet:0");
if (address(managementFeeWallet) == 0)
doThrow("managementFeeWallet:0");
}
function () returns (bool success) {
if (!isFromManagedAccount()) {
// We do not accept donation here. Any extra amount sent to us after fund locking process, will be refunded
return createTokenProxy(msg.sender);
}
else {
evRecord(msg.sender, msg.value, "Recevied ether from ManagedAccount");
return true;
}
}
function isFromManagedAccount() internal returns (bool) {
return msg.sender == address(extraBalanceWallet)
|| msg.sender == address(returnWallet)
|| msg.sender == address(rewardWallet)
|| msg.sender == address(managementFeeWallet);
}
/*
* Voting for some critical steps, on blockchain
*/
function voteToKickoffNewFiscalYear() onlyTokenHolders noEther onlyLocked {
// this is the only valid fiscal year parameter, so there's no point in letting the caller pass it in.
// Best case is they get it wrong and we throw, worst case is the get it wrong and there's some exploit
uint _fiscal = currentFiscalYear + 1;
if(!isKickoffEnabled[1]){ // if the first fiscal year is not kicked off yet
// accept voting
}else if(currentFiscalYear <= 3){ // if there was any kickoff() enabled before already
if(lastKickoffDate + lastKickoffDateBuffer < now){ // 2 months from the end of the fiscal year
// accept voting
}else{
// we do not accept early kickoff
doThrow("kickOff:tooEarly");
return;
}
}else{
// do not accept kickoff anymore after the 4th year
doThrow("kickOff:4thYear");
return;
}
supportKickoffQuorum[_fiscal] -= votedKickoff[_fiscal][msg.sender];
supportKickoffQuorum[_fiscal] += balances[msg.sender];
votedKickoff[_fiscal][msg.sender] = balances[msg.sender];
uint threshold = (kickoffQuorumPercent*(tokensCreated + bountyTokensCreated)) / 100;
if(supportKickoffQuorum[_fiscal] > threshold) {
if(_fiscal == 1){
// transfer fund in extraBalance to main account
extraBalanceWallet.returnBalanceToMainAccount();
// reserve mgmtFeePercentage of whole fund to ManagementFeePoolWallet
totalInitialBalance = this.balance;
uint fundToReserve = (totalInitialBalance * mgmtFeePercentage) / 100;
annualManagementFee = fundToReserve / 4;
if(!managementFeeWallet.send(fundToReserve)){
doThrow("kickoff:ManagementFeePoolWalletFail");
return;
}
}
isKickoffEnabled[_fiscal] = true;
currentFiscalYear = _fiscal;
lastKickoffDate = now;
// transfer annual management fee from reservedWallet to mgmtWallet (external)
managementFeeWallet.payManagementBodyAmount(annualManagementFee);
evKickoff(msg.sender, msg.value, _fiscal);
evIssueManagementFee(msg.sender, msg.value, annualManagementFee, true);
}
}
function voteToFreezeFund() onlyTokenHolders noEther onlyLocked notFinalFiscalYear onlyDistributionNotInProgress {
supportFreezeQuorum -= votedFreeze[msg.sender];
supportFreezeQuorum += balances[msg.sender];
votedFreeze[msg.sender] = balances[msg.sender];
uint threshold = ((tokensCreated + bountyTokensCreated) * freezeQuorumPercent) / 100;
if(supportFreezeQuorum > threshold){
isFreezeEnabled = true;
distributeDownstream(0);
evFreeze(msg.sender, msg.value);
}
}
function recallVoteToFreezeFund() onlyTokenHolders onlyNotFrozen noEther {
supportFreezeQuorum -= votedFreeze[msg.sender];
votedFreeze[msg.sender] = 0;
}
function voteToHarvestFund() onlyTokenHolders noEther onlyLocked onlyFinalFiscalYear {
supportHarvestQuorum -= votedHarvest[msg.sender];
supportHarvestQuorum += balances[msg.sender];
votedHarvest[msg.sender] = balances[msg.sender];
uint threshold = ((tokensCreated + bountyTokensCreated) * harvestQuorumPercent) / 100;
if(supportHarvestQuorum > threshold) {
isHarvestEnabled = true;
evHarvest(msg.sender, msg.value);
}
}
function collectMyReturn() onlyTokenHolders noEther onlyDistributionReady {
uint tokens = balances[msg.sender];
balances[msg.sender] = 0;
returnWallet.payTokenHolderBasedOnTokenCount(msg.sender, tokens);
}
function mgmtInvestProject(
address _projectWallet,
uint _amount
) onlyManagementBody hasEther returns (bool _success) {
if(!isKickoffEnabled[currentFiscalYear] || isFreezeEnabled || isHarvestEnabled){
evMgmtInvestProject(msg.sender, msg.value, _projectWallet, _amount, false);
return;
}
if(_amount >= this.balance){
doThrow("failed:mgmtInvestProject: amount >= actualBalance");
return;
}
// send the balance (_amount) to _projectWallet
if (!_projectWallet.call.value(_amount)()) {
doThrow("failed:mgmtInvestProject: cannot send to _projectWallet");
return;
}
evMgmtInvestProject(msg.sender, msg.value, _projectWallet, _amount, true);
}
function transfer(address _to, uint256 _value) returns (bool success) {
// Update kickoff voting record for the next fiscal year for an address, and the total quorum
if(currentFiscalYear < 4){
if(votedKickoff[currentFiscalYear+1][msg.sender] > _value){
votedKickoff[currentFiscalYear+1][msg.sender] -= _value;
supportKickoffQuorum[currentFiscalYear+1] -= _value;
}else{
supportKickoffQuorum[currentFiscalYear+1] -= votedKickoff[currentFiscalYear+1][msg.sender];
votedKickoff[currentFiscalYear+1][msg.sender] = 0;
}
}
// Update Freeze and Harvest voting records for an address, and the total quorum
if(votedFreeze[msg.sender] > _value){
votedFreeze[msg.sender] -= _value;
supportFreezeQuorum -= _value;
}else{
supportFreezeQuorum -= votedFreeze[msg.sender];
votedFreeze[msg.sender] = 0;
}
if(votedHarvest[msg.sender] > _value){
votedHarvest[msg.sender] -= _value;
supportHarvestQuorum -= _value;
}else{
supportHarvestQuorum -= votedHarvest[msg.sender];
votedHarvest[msg.sender] = 0;
}
if (isFundLocked && super.transfer(_to, _value)) {
return true;
} else {
if(!isFundLocked){
doThrow("failed:transfer: isFundLocked is false");
}else{
doThrow("failed:transfer: cannot send send to _projectWallet");
}
return;
}
}
}
|
Business logic (but no state changes) setup transaction details Sell tokens in batches based on the current price. special case. Allow the last purchase to go over the max External calls
|
function createTokenProxy(address _tokenHolder) internal notLocked notReleased hasEther returns (bool success) {
uint tokensSupplied = 0;
uint weiAccepted = 0;
bool wasMinTokensReached = isMinTokensReached();
var weiPerLatestHONG = weiPerInitialHONG * divisor() / 100;
uint remainingWei = msg.value;
uint tokensAvailable = tokensAvailableAtCurrentTier();
if (tokensAvailable == 0) {
doThrow("noTokensToSell");
return false;
}
while (remainingWei >= weiPerLatestHONG) {
uint tokensRequested = remainingWei / weiPerLatestHONG;
uint tokensToSellInBatch = min(tokensAvailable, tokensRequested);
if (tokensAvailable == 0 && tokensCreated == maxTokensToCreate) {
tokensToSellInBatch = tokensRequested;
}
uint priceForBatch = tokensToSellInBatch * weiPerLatestHONG;
tokensSupplied += tokensToSellInBatch;
tokensCreated += tokensToSellInBatch;
weiGiven[_tokenHolder] += priceForBatch;
remainingWei = msg.value - weiAccepted;
tokensAvailable = tokensAvailableAtCurrentTier();
}
taxPaid[_tokenHolder] += totalTaxLevied;
if (totalTaxLevied > 0) {
if (!extraBalanceWallet.send(totalTaxLevied)){
doThrow("extraBalance:sendFail");
return;
}
}
if (!wasMinTokensReached && isMinTokensReached()) evMinTokensReached(msg.sender, msg.value, tokensCreated);
if (isFundLocked) evLockFund(msg.sender, msg.value);
if (isFundReleased) evReleaseFund(msg.sender, msg.value);
return true;
}
| 1,796,445
|
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./interface/IiToken.sol";
import "./interface/IRewardDistributor.sol";
import "./interface/IPriceOracle.sol";
import "./library/Initializable.sol";
import "./library/Ownable.sol";
import "./library/SafeRatioMath.sol";
import "./Controller.sol";
/**
* @title dForce's lending reward distributor Contract
* @author dForce
*/
contract RewardDistributor is Initializable, Ownable, IRewardDistributor {
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice the controller
Controller public controller;
/// @notice the global Reward distribution speed
uint256 public globalDistributionSpeed;
/// @notice the Reward distribution speed of each iToken
mapping(address => uint256) public distributionSpeed;
/// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa
mapping(address => uint256) public distributionFactorMantissa;
struct DistributionState {
// Token's last updated index, stored as a mantissa
uint256 index;
// The block number the index was last updated at
uint256 block;
}
/// @notice the Reward distribution supply state of each iToken
mapping(address => DistributionState) public distributionSupplyState;
/// @notice the Reward distribution borrow state of each iToken
mapping(address => DistributionState) public distributionBorrowState;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionSupplierIndex;
/// @notice the Reward distribution state of each account of each iToken
mapping(address => mapping(address => uint256))
public distributionBorrowerIndex;
/// @notice the Reward distributed into each account
mapping(address => uint256) public reward;
/// @notice the Reward token address
address public rewardToken;
/// @notice whether the reward distribution is paused
bool public paused;
/// @notice the Reward distribution speed supply side of each iToken
mapping(address => uint256) public distributionSupplySpeed;
/// @notice the global Reward distribution speed for supply
uint256 public globalDistributionSupplySpeed;
/**
* @dev Throws if called by any account other than the controller.
*/
modifier onlyController() {
require(
address(controller) == msg.sender,
"onlyController: caller is not the controller"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize(Controller _controller) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
__Ownable_init();
controller = _controller;
paused = true;
}
/**
* @notice set reward token address
* @dev Admin function, only owner can call this
* @param _newRewardToken the address of reward token
*/
function _setRewardToken(address _newRewardToken)
external
override
onlyOwner
{
address _oldRewardToken = rewardToken;
require(
_newRewardToken != address(0) && _newRewardToken != _oldRewardToken,
"Reward token address invalid"
);
rewardToken = _newRewardToken;
emit NewRewardToken(_oldRewardToken, _newRewardToken);
}
/**
* @notice Add the iToken as receipient
* @dev Admin function, only controller can call this
* @param _iToken the iToken to add as recipient
* @param _distributionFactor the distribution factor of the recipient
*/
function _addRecipient(address _iToken, uint256 _distributionFactor)
external
override
onlyController
{
distributionFactorMantissa[_iToken] = _distributionFactor;
distributionSupplyState[_iToken] = DistributionState({
index: 0,
block: block.number
});
distributionBorrowState[_iToken] = DistributionState({
index: 0,
block: block.number
});
emit NewRecipient(_iToken, _distributionFactor);
}
/**
* @notice Pause the reward distribution
* @dev Admin function, pause will set global speed to 0 to stop the accumulation
*/
function _pause() external override onlyOwner {
// Set the global distribution speed to 0 to stop accumulation
_setGlobalDistributionSpeeds(0, 0);
_setPaused(true);
}
/**
* @notice Unpause and set global distribution speed
* @dev Admin function
* @param _borrowSpeed The speed of Reward distribution to borrow side per second
* @param _supplySpeed The speed of Reward distribution to supply side per second
*/
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed)
external
override
onlyOwner
{
_setPaused(false);
_setGlobalDistributionSpeeds(_borrowSpeed, _supplySpeed);
}
/**
* @notice Pause/Unpause the reward distribution
* @dev Admin function
* @param _paused whether to pause/unpause the distribution
*/
function _setPaused(bool _paused) internal {
paused = _paused;
emit Paused(_paused);
}
/**
* @notice Sets the global distribution speed, updating each iToken's speed accordingly
* @dev Admin function, will fail when paused
* @param _supplySpeed The speed of Reward distribution to supply side per second
* @param _borrowSpeed The speed of Reward distribution to borrow side per per second
*/
function _setGlobalDistributionSpeeds(
uint256 _borrowSpeed,
uint256 _supplySpeed
) public override onlyOwner {
require(!paused, "Can not change global speed when paused");
globalDistributionSpeed = _borrowSpeed;
globalDistributionSupplySpeed = _supplySpeed;
_updateDistributionSpeed();
emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed);
}
/**
* @notice Update each iToken's distribution speed according to current global speed
* @dev Only EOA can call this function
*/
function updateDistributionSpeed() public override {
require(msg.sender == tx.origin, "only EOA can update speeds");
require(!paused, "Can not update speeds when paused");
// Do the actual update
_updateDistributionSpeed();
}
/**
* @notice Internal function to update each iToken's distribution speed
*/
function _updateDistributionSpeed() internal {
address[] memory _iTokens = controller.getAlliTokens();
uint256 _globalBorrowSpeed = globalDistributionSpeed;
uint256 _globalSupplySpeed = globalDistributionSupplySpeed;
uint256 _len = _iTokens.length;
uint256[] memory _tokenBorrowValues = new uint256[](_len);
uint256 _totalBorrowValue;
uint256[] memory _tokenSupplyValues = new uint256[](_len);
uint256 _totalSupplyValue;
// Calculates the total value and token value
// tokenValue = tokenTotalBorrow * price * tokenDistributionFactorMantissa
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_iTokens[i]);
// Update both supply and borrow state before updating new speed
_updateDistributionState(address(_token), true);
_updateDistributionState(address(_token), false);
uint256 _totalBorrow = _token.totalBorrows();
uint256 _totalSupply = IERC20Upgradeable(_iTokens[i]).totalSupply();
// It is okay if the underlying price is 0
uint256 _underlyingPrice =
IPriceOracle(controller.priceOracle()).getUnderlyingPrice(
address(_token)
);
_tokenBorrowValues[i] = _totalBorrow.mul(_underlyingPrice).rmul(
distributionFactorMantissa[address(_token)]
);
_tokenSupplyValues[i] = _totalSupply
.rmul(_token.exchangeRateStored())
.mul(_underlyingPrice)
.rmul(distributionFactorMantissa[address(_token)]);
_totalBorrowValue = _totalBorrowValue.add(_tokenBorrowValues[i]);
_totalSupplyValue = _totalSupplyValue.add(_tokenSupplyValues[i]);
}
// Calculates the distribution speed for each token
for (uint256 i = 0; i < _len; i++) {
address _token = _iTokens[i];
uint256 _borrowSpeed =
_totalBorrowValue > 0
? _globalBorrowSpeed.mul(_tokenBorrowValues[i]).div(
_totalBorrowValue
)
: 0;
distributionSpeed[_token] = _borrowSpeed;
uint256 _supplySpeed =
_totalSupplyValue > 0
? _globalSupplySpeed.mul(_tokenSupplyValues[i]).div(
_totalSupplyValue
)
: 0;
distributionSupplySpeed[_token] = _supplySpeed;
emit DistributionSpeedsUpdated(_token, _borrowSpeed, _supplySpeed);
}
}
/**
* @notice Sets the distribution factor for a iToken
* @dev Admin function to set distribution factor for a iToken
* @param _iToken The token to set the factor on
* @param _newDistributionFactorMantissa The new distribution factor, scaled by 1e18
*/
function _setDistributionFactor(
address _iToken,
uint256 _newDistributionFactorMantissa
) internal {
// iToken must have been listed
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _oldDistributionFactorMantissa =
distributionFactorMantissa[_iToken];
distributionFactorMantissa[_iToken] = _newDistributionFactorMantissa;
emit NewDistributionFactor(
_iToken,
_oldDistributionFactorMantissa,
_newDistributionFactorMantissa
);
}
/**
* @notice Sets the distribution factors for a list of iTokens
* @dev Admin function to set distribution factors for a list of iTokens
* @param _iTokens The list of tokens to set the factor on
* @param _distributionFactors The list of distribution factors, scaled by 1e18
*/
function _setDistributionFactors(
address[] calldata _iTokens,
uint256[] calldata _distributionFactors
) external override onlyOwner {
require(
_iTokens.length == _distributionFactors.length,
"Length of _iTokens and _distributionFactors mismatch"
);
require(!paused, "Can not update distribution factors when paused");
uint256 _len = _iTokens.length;
for (uint256 i = 0; i < _len; i++) {
_setDistributionFactor(_iTokens[i], _distributionFactors[i]);
}
// Update the distribution speed of all iTokens
_updateDistributionSpeed();
}
/**
* @notice Update the iToken's Reward distribution state
* @dev Will be called every time when the iToken's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateDistributionState(address _iToken, bool _isBorrow)
external
override
{
// Skip all updates if it is paused
if (paused) {
return;
}
_updateDistributionState(_iToken, _isBorrow);
}
function _updateDistributionState(address _iToken, bool _isBorrow)
internal
{
require(controller.hasiToken(_iToken), "Token has not been listed");
DistributionState storage state =
_isBorrow
? distributionBorrowState[_iToken]
: distributionSupplyState[_iToken];
uint256 _speed =
_isBorrow
? distributionSpeed[_iToken]
: distributionSupplySpeed[_iToken];
uint256 _blockNumber = block.number;
uint256 _deltaBlocks = _blockNumber.sub(state.block);
if (_deltaBlocks > 0 && _speed > 0) {
uint256 _totalToken =
_isBorrow
? IiToken(_iToken).totalBorrows().rdiv(
IiToken(_iToken).borrowIndex()
)
: IERC20Upgradeable(_iToken).totalSupply();
uint256 _totalDistributed = _speed.mul(_deltaBlocks);
// Reward distributed per token since last time
uint256 _distributedPerToken =
_totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0;
state.index = state.index.add(_distributedPerToken);
}
state.block = _blockNumber;
}
/**
* @notice Update the account's Reward distribution state
* @dev Will be called every time when the account's supply/borrow changes
* @param _iToken The iToken to be updated
* @param _account The account to be updated
* @param _isBorrow whether to update the borrow state
*/
function updateReward(
address _iToken,
address _account,
bool _isBorrow
) external override {
_updateReward(_iToken, _account, _isBorrow);
}
function _updateReward(
address _iToken,
address _account,
bool _isBorrow
) internal {
require(_account != address(0), "Invalid account address!");
require(controller.hasiToken(_iToken), "Token has not been listed");
uint256 _iTokenIndex;
uint256 _accountIndex;
uint256 _accountBalance;
if (_isBorrow) {
_iTokenIndex = distributionBorrowState[_iToken].index;
_accountIndex = distributionBorrowerIndex[_iToken][_account];
_accountBalance = IiToken(_iToken)
.borrowBalanceStored(_account)
.rdiv(IiToken(_iToken).borrowIndex());
// Update the account state to date
distributionBorrowerIndex[_iToken][_account] = _iTokenIndex;
} else {
_iTokenIndex = distributionSupplyState[_iToken].index;
_accountIndex = distributionSupplierIndex[_iToken][_account];
_accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Update the account state to date
distributionSupplierIndex[_iToken][_account] = _iTokenIndex;
}
uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex);
uint256 _amount = _accountBalance.rmul(_deltaIndex);
if (_amount > 0) {
reward[_account] = reward[_account].add(_amount);
emit RewardDistributed(_iToken, _account, _amount, _accountIndex);
}
}
/**
* @notice Update reward accrued in iTokens by the holders regardless of paused or not
* @param _holders The account to update
* @param _iTokens The _iTokens to update
*/
function updateRewardBatch(
address[] memory _holders,
address[] memory _iTokens
) public override {
// Update rewards for all _iTokens for holders
for (uint256 i = 0; i < _iTokens.length; i++) {
address _iToken = _iTokens[i];
_updateDistributionState(_iToken, false);
_updateDistributionState(_iToken, true);
for (uint256 j = 0; j < _holders.length; j++) {
_updateReward(_iToken, _holders[j], false);
_updateReward(_iToken, _holders[j], true);
}
}
}
/**
* @notice Claim reward accrued in iTokens by the holders
* @param _holders The account to claim for
* @param _iTokens The _iTokens to claim from
*/
function claimReward(address[] memory _holders, address[] memory _iTokens)
public
override
{
updateRewardBatch(_holders, _iTokens);
// Withdraw all reward for all holders
for (uint256 j = 0; j < _holders.length; j++) {
address _account = _holders[j];
uint256 _reward = reward[_account];
if (_reward > 0) {
reward[_account] = 0;
IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward);
}
}
}
/**
* @notice Claim reward accrued in all iTokens by the holders
* @param _holders The account to claim for
*/
function claimAllReward(address[] memory _holders) external override {
claimReward(_holders, controller.getAlliTokens());
}
}
|
Unpause and set global distribution speed Admin function _borrowSpeed The speed of Reward distribution to borrow side per second _supplySpeed The speed of Reward distribution to supply side per second/
|
function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed)
external
override
onlyOwner
{
_setPaused(false);
_setGlobalDistributionSpeeds(_borrowSpeed, _supplySpeed);
}
| 6,366,957
|
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/FundMarketplace.sol";
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract TestFundMarketplace {
//State Variables
//FundMarketplace contract
FundMarketplace fm;
//Manager contract (at bottom)
Manager manager;
//Investor contract (at bottom)
Investor investor;
address managerAddr;
address investorAddr;
uint public initialBalance = 10 ether;
uint fundNum;
bytes32 a; //name
address b; //fundOwner
uint c; //totalCapital
uint d; //capitalDeployed
uint e; //Fee Rate
uint f; //Payment Cycle
bool g; //Investor Status
uint h; //Virtual Balance
uint i; //Investor Fees
bytes32 j; //digest of ipfs hash
uint8 k; //hashfunction
uint8 l; //hash function size
function beforeAll() public {
//Deploy FundMarketplace contracts
fm = FundMarketplace(DeployedAddresses.FundMarketplace());
//Deploy Manager and Investor contracts
manager = new Manager();
//Give the manager some ether
address(manager).transfer(2 ether);
investor = new Investor();
//Give the investor some ether
address(investor).transfer(3 ether);
managerAddr = address(manager);
investorAddr = address(investor);
}
function testInitializeFund() public{
//Manager initializes new fund
fundNum = 1;
bytes32 name = "alpha";
uint initialFund = 1 ether;
//feeRate is 2%
uint feeRate = 2;
//paymentCycle is in unit of days
//made it zero days for testing purposes
uint paymentCycle = 30;
//Multihash
bytes32 digest = 0x7D5A99F603F231D53A4F39D1521F98D2E8BB279CF29BEBFD0687DC98458E7F89;
uint8 hash_function = 0x12;
uint8 size = 0x20;
manager.initializeFund(fm, name, initialFund, feeRate, paymentCycle, digest, hash_function, size);
(a,b,c,d,e,f) = fm.getFundDetails(fundNum);
(g,h,i) = fm. getFundDetails2(fundNum, managerAddr);
(j,k,l) = fm.getIpfsHash(fundNum);
//Tests
Assert.equal(a, name, "Strategy name does not match test name");
Assert.equal(b, managerAddr, "Manager is not owner of strategy");
Assert.equal(c, initialFund, "Strategy funds do not match test funds");
Assert.equal(d, 0, "Deployed Capital is not equal to zero");
Assert.equal(e, feeRate, "Fee Rate does not match test rate");
Assert.equal(f, paymentCycle, "Payment Cycle does not match test cycle");
Assert.equal(g, true, "Manager is not listed as investor");
Assert.equal(h, initialFund, "Manager's funds are not listed");
Assert.equal(i, 0, "Manager's fees deposited are not zero");
Assert.equal(j, digest, "digest of ipfs hash does not match test value");
Assert.equal(uint(k), uint(hash_function), "hash_function of ipfs hash does not match test value");
Assert.equal(uint(l), uint(size), "size of ipfs hash does not match test value");
}
function testInvestment() public{
//Investor account will invest 2 ether into Fund Number 1
uint investment = 2 ether;
(,,c,,,) = fm.getFundDetails(fundNum);
(g,h,i) = fm.getFundDetails2(fundNum, investorAddr);
//Tests
Assert.equal(c, 1 ether, "Initial account fund does not match initial balance");
Assert.equal(g, false, "Account is incorrectly listed as investor");
Assert.equal(h, 0, "Investor's virtual balance is not zero");
Assert.equal(i, 0, "Investor's fees are not zero");
//Make an actual investment
investor.makeInvestment(fm, fundNum, investment);
//Tests
(,,c,,,) = fm.getFundDetails(fundNum);
(g,h,i) = fm.getFundDetails2(fundNum, investorAddr);
//Tests
Assert.equal(c, 3 ether, "Funds do not match sum of virtual balances");
Assert.equal(g, true, "Account is not listed as investor");
Assert.equal(h, 2 ether, "Investor's virtual balance does not match investment");
Assert.equal(i, SafeMath.add(SafeMath.div(investment, fm.checkFeeRate(fundNum)), 1), "Investor's fees were not valid");
}
function testPlaceOrder() public {
//Manager will place an order for the following "Buy 3 PLNT at an execution price of 100 finney"
bytes32 action = "buy";
bytes32 ticker = "PLNT";
uint qty = 3;
//Price of individual security
uint price = 100 finney; //0.0001 ether
//Test to make sure deployed capital is zero
uint capDeploy;
(,,,capDeploy,,) = fm.getFundDetails(fundNum);
Assert.equal(capDeploy, 0, "Capital Deployed is not 0");
manager.placeOrder(fm, fundNum, action, ticker, qty, price);
//Read Capital Deployed
(,,,capDeploy,,) = fm.getFundDetails(fundNum);
//Check to make sure capital was deployed
Assert.equal(capDeploy, SafeMath.mul(price,qty), "Capital was not successfully deployed");
}
function testReceiveOrder() public {
//Orders are received by listening for events
//Therefore cannot test for receiving the actual order
//Test for calculating correct quantity of shares for investor order based on share of capital in fund
uint qty = 3;
uint actual = 2;
uint test = investor.calcQty(fm, fundNum, qty);
Assert.equal(test, actual, "Wrong quantity returned");
}
function testWithdrawFunds() public {
//Test for both a partial and a full withdrawal
//Investor's pre-withdrawal balance
uint preBalance = investorAddr.balance;
//Partial withdrawal amount
uint amount = 1 ether;
uint currentFees;
(,,currentFees) = fm.getFundDetails2(fundNum, investorAddr);
//investor withdraw a portion of his funds
investor.withdrawFunds(fm, fundNum, amount);
uint midBalance = investorAddr.balance;
//Tests
(,,c,,,) = fm.getFundDetails(fundNum);
(g,h,i) = fm.getFundDetails2(fundNum, investorAddr);
Assert.equal(c, 2 ether, "Funds do not match sum of virtual balances");
Assert.equal(g, true, "Account should still be listed as an investor");
Assert.equal(h, 1 ether, "Investor's should not be zeroed out");
Assert.equal(i, currentFees, "Investor's fees should not change");
Assert.equal(midBalance, preBalance, "Midbalance should be equal to preBalance");
//investor withdraws remainder of funds
investor.withdrawFunds(fm, fundNum, amount);
uint postBalance = investorAddr.balance;
//Tests
(,,c,,,) = fm.getFundDetails(fundNum);
(g,h,i) = fm.getFundDetails2(fundNum, investorAddr);
//Tests
Assert.equal(c, 1 ether, "Funds do not match sum of virtual balances");
Assert.equal(g, false, "Account falsely remain an investor");
Assert.equal(h, 0, "Investor's virtual balance is not zeroed out");
Assert.equal(i, 0, "Investor's fees are not zeroed out");
//confirm fees were refunded
Assert.isAbove(postBalance, preBalance, "Investor's fees were not transferred back successfully");
}
function testCloseFund() public {
//Test to verify a manager can close a fund and that the fundCount decreases
//Tests
(,g) = fm.checkFundStatus(fundNum);
uint fundCount_old = fm.fundCount();
Assert.equal(g, false, "Fund Details were incorrect");
//Delete Fund
manager.closeFund(fm, fundNum);
//Tests
(,g) = fm.checkFundStatus(fundNum);
uint fundCount_new = fm.fundCount();
Assert.equal(g, true, "Fund Details were incorrect");
Assert.equal(fundCount_new, fundCount_old-1, "Fund count was not correctly updated");
}
}
contract Manager {
//All functions call functions in FundMarketplace.sol from manager address
function initializeFund(FundMarketplace fm, bytes32 _name, uint _initalFund, uint _feeRate, uint _paymentCycle, bytes32 _digest, uint8 _hash_function, uint8 _size)
external
{
fm.initializeFund(_name, address(this), _initalFund, _feeRate, _paymentCycle, _digest, _hash_function, _size);
}
function placeOrder(FundMarketplace fm, uint _fundNum, bytes32 _action, bytes32 _ticker, uint _qty, uint _price)
external
{
fm.placeOrder(_fundNum, _action, _ticker, _qty, _price);
}
function closeFund(FundMarketplace fm, uint _fundNum)
external
{
fm.closeFund(_fundNum);
}
//Fallback function, accepts ether
function() external payable {
}
}
contract Investor {
//All functions call functions in FundMarketplace.sol from investor address
function makeInvestment(FundMarketplace fm, uint _fundNum, uint _investment)
external
{
//Fee calculated by dividing investment by the result from checkFeeRate() and adding 1 to round
uint fee = SafeMath.add(SafeMath.div(_investment, fm.checkFeeRate(_fundNum)), 1);
fm.Invest.value(fee)(_fundNum, _investment);
}
function withdrawFunds(FundMarketplace fm, uint _fundNum, uint _amount)
external
{
fm.withdrawFunds(_fundNum, _amount);
}
//Calculates the quantity of shares an investor will receive in their customized order
function calcQty(FundMarketplace fm, uint _fundNum, uint qty)
external view returns (uint)
{
return fm.calcQty(_fundNum, qty);
}
//Fallback function, accepts ether
function() external payable{
}
}
|
Test to verify a manager can close a fund and that the fundCount decreasesTestsDelete FundTests
|
function testCloseFund() public {
(,g) = fm.checkFundStatus(fundNum);
uint fundCount_old = fm.fundCount();
Assert.equal(g, false, "Fund Details were incorrect");
manager.closeFund(fm, fundNum);
(,g) = fm.checkFundStatus(fundNum);
uint fundCount_new = fm.fundCount();
Assert.equal(g, true, "Fund Details were incorrect");
Assert.equal(fundCount_new, fundCount_old-1, "Fund count was not correctly updated");
}
| 5,460,861
|
/**
*Submitted for verification at Etherscan.io on 2021-05-17
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts\utils\Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts\interfaces\IRewarder.sol
pragma solidity 0.6.12;
interface IRewarder {
using SafeERC20 for IERC20;
function onReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external;
function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory);
}
// File: contracts\ConvexMasterChef.sol
pragma solidity 0.6.12;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ConvexMasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CVXs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCvxPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCvxPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CVX to distribute per block.
uint256 lastRewardBlock; // Last block number that CVXs distribution occurs.
uint256 accCvxPerShare; // Accumulated CVXs per share, times 1e12. See below.
IRewarder rewarder;
}
//cvx
IERC20 public cvx;
// Block number when bonus CVX period ends.
uint256 public bonusEndBlock;
// CVX tokens created per block.
uint256 public rewardPerBlock;
// Bonus muliplier for early cvx makers.
uint256 public constant BONUS_MULTIPLIER = 2;
// Info of each pool.
PoolInfo[] public poolInfo;
// 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 = 0;
// The block number when CVX mining starts.
uint256 public startBlock;
// Events
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
IERC20 _cvx,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
cvx = _cvx;
rewardPerBlock = _rewardPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
IRewarder _rewarder,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvxPerShare: 0,
rewarder: _rewarder
})
);
}
// Update the given pool's CVX allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool _withUpdate,
bool _updateRewarder
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
if(_updateRewarder){
poolInfo[_pid].rewarder = _rewarder;
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending CVXs on frontend.
function pendingCvx(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCvxPerShare = pool.accCvxPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 cvxReward = multiplier
.mul(rewardPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accCvxPerShare = accCvxPerShare.add(
cvxReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accCvxPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvxReward = multiplier
.mul(rewardPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
//cvx.mint(address(this), cvxReward);
pool.accCvxPerShare = pool.accCvxPerShare.add(
cvxReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for CVX allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accCvxPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeRewardTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, 0, user.amount);
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvxPerShare).div(1e12).sub(
user.rewardDebt
);
safeRewardTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, pending, user.amount);
}
emit RewardPaid(msg.sender, _pid, pending);
emit Withdraw(msg.sender, _pid, _amount);
}
function claim(uint256 _pid, address _account) external{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_account];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvxPerShare).div(1e12).sub(
user.rewardDebt
);
safeRewardTransfer(_account, pending);
user.rewardDebt = user.amount.mul(pool.accCvxPerShare).div(1e12);
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, _account, _account, pending, user.amount);
}
emit RewardPaid(_account, _pid, pending);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
//extra rewards
IRewarder _rewarder = pool.rewarder;
if (address(_rewarder) != address(0)) {
_rewarder.onReward(_pid, msg.sender, msg.sender, 0, 0);
}
}
// Safe cvx transfer function, just in case if rounding error causes pool to not have enough CVXs.
function safeRewardTransfer(address _to, uint256 _amount) internal {
uint256 cvxBal = cvx.balanceOf(address(this));
if (_amount > cvxBal) {
cvx.safeTransfer(_to, cvxBal);
} else {
cvx.safeTransfer(_to, _amount);
}
}
}
|
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
|
function add(
uint256 _allocPoint,
IERC20 _lpToken,
IRewarder _rewarder,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvxPerShare: 0,
rewarder: _rewarder
})
);
}
| 2,194,055
|
./partial_match/3/0xD675a50E477c035BCAA8191a9715306640683732/sources/Lock.sol
|
Returns fee per lock in bsov token of BSOV tokens/
|
function getBsovTokenFee() external view returns(uint256) {
return _bsovTokenFee;
}
| 5,119,527
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./exchange/Exchange.sol";
import "./registry/ProxyRegistry.sol";
import "./modules/TokenTransferProxy.sol";
import "./modules/ERC20.sol";
contract PaceArtExchange is Exchange {
string public constant name = "Project Wyvern Exchange";
string public constant version = "2.2";
string public constant codename = "Lambton Worm";
/**
* @dev Initialize a WyvernExchange instance
* @param registryAddress Address of the registry instance which this Exchange instance will use
* @param tokenAddress Address of the token used for protocol fees
*/
constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress) {
registry = registryAddress;
tokenTransferProxy = tokenTransferProxyAddress;
exchangeToken = tokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../libraries/ReentrancyGuarded.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/TokenTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ExchangeCore.sol";
import "hardhat/console.sol";
contract Exchange is ExchangeCore {
// /**
// * @dev Call guardedArrayReplace - library function exposed for testing.
// */
// function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask)
// public
// pure
// returns (bytes memory)
// {
// ArrayUtils.guardedArrayReplace(array, desired, mask);
// return array;
// }
// /**
// * Test copy byte array
// *
// * @param arrToCopy Array to copy
// * @return byte array
// */
// function testCopy(bytes memory arrToCopy)
// public
// pure
// returns (bytes memory)
// {
// bytes memory arr = new bytes(arrToCopy.length);
// uint index;
// assembly {
// index := add(arr, 0x20)
// }
// ArrayUtils.unsafeWriteBytes(index, arrToCopy);
// return arr;
// }
// /**
// * Test write address to bytes
// *
// * @param addr Address to write
// * @return byte array
// */
// function testCopyAddress(address addr)
// public
// pure
// returns (bytes memory)
// {
// bytes memory arr = new bytes(0x14);
// uint index;
// assembly {
// index := add(arr, 0x20)
// }
// ArrayUtils.unsafeWriteAddress(index, addr);
// return arr;
// }
/**
* @dev Call calculateFinalPrice - library function exposed for testing.
*/
function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime)
public
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime);
}
/**
* @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashOrder_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
pure
returns (bytes32)
{
return hashOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashToSign_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
pure
returns (bytes32)
{
return hashToSign(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrderParameters_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
view
public
returns (bool)
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return validateOrderParameters(
order
);
}
/**
* @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrder_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s)
view
public
returns (bool)
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return validateOrder(
hashToSign(order),
order,
Sig(v, r, s)
);
}
/**
* @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function approveOrder_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
bool orderbookInclusionDesired)
public
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return approveOrder(order, orderbookInclusionDesired);
}
/**
* @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function cancelOrder_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s)
public
{
return cancelOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]),
Sig(v, r, s)
);
}
/**
* @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateCurrentPrice_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
view
returns (uint)
{
return calculateCurrentPrice(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function ordersCanMatch_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell)
public
view
returns (bool)
{
Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]);
return ordersCanMatch(
buy,
sell
);
}
/**
* @dev Return whether or not two orders' calldata specifications can match
* @param buyCalldata Buy-side order calldata
* @param buyReplacementPattern Buy-side order calldata replacement mask
* @param sellCalldata Sell-side order calldata
* @param sellReplacementPattern Sell-side order calldata replacement mask
* @return Whether the orders' calldata can be matched
*/
function orderCalldataCanMatch(bytes memory buyCalldata, bytes memory buyReplacementPattern, bytes memory sellCalldata, bytes memory sellReplacementPattern)
public
pure
returns (bool)
{
if (buyReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern);
}
if (sellReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern);
}
return ArrayUtils.arrayEq(buyCalldata, sellCalldata);
}
/**
* @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateMatchPrice_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell)
public
view
returns (uint)
{
Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]);
return calculateMatchPrice(
buy,
sell
);
}
/**
* @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function atomicMatch_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell,
uint8[2] memory vs,
bytes32[5] memory rssMetadata)
public
payable
{
return atomicMatch(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
}
/*
Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them.
Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OwnableDelegateProxy.sol";
import "./ProxyRegistryInterface.sol";
/**
* @title ProxyRegistry
* @author Wyvern Protocol Developers
*/
contract ProxyRegistry is Ownable, ProxyRegistryInterface {
/* DelegateProxy implementation contract. Must be initialized. */
address public override delegateProxyImplementation;
/* Authenticated proxies by user. */
mapping(address => OwnableDelegateProxy) public override proxies;
/* Contracts pending access. */
mapping(address => uint) public pending;
/* Contracts allowed to call those proxies. */
mapping(address => bool) public contracts;
/* Delay period for adding an authenticated contract.
This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO),
a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have
plenty of time to notice and transfer their assets.
*/
uint public DELAY_PERIOD = 2 weeks;
/**
* Start the process to enable access for specified contract. Subject to delay period.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function startGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] == 0, "Contract is already allowed in registry, or pending");
pending[addr] = block.timestamp;
}
/**
* End the process to enable access for specified contract after delay period has passed.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function endGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp), "Contract is no longer pending or has already been approved by registry");
pending[addr] = 0;
contracts[addr] = true;
}
/**
* Revoke access for specified contract. Can be done instantly.
*
* @dev ProxyRegistry owner only
* @param addr Address of which to revoke permissions
*/
function revokeAuthentication (address addr)
public
onlyOwner
{
contracts[addr] = false;
}
/**
* Register a proxy contract with this registry
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxy()
public
returns (OwnableDelegateProxy proxy)
{
return registerProxyFor(msg.sender);
}
/**
* Register a proxy contract with this registry, overriding any existing proxy
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyOverride()
public
returns (OwnableDelegateProxy proxy)
{
proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this)));
proxies[msg.sender] = proxy;
return proxy;
}
/**
* Register a proxy contract with this registry
*
* @dev Can be called by any user
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyFor(address user)
public
returns (OwnableDelegateProxy proxy)
{
require(proxies[user] == OwnableDelegateProxy(0), "User already has a proxy");
proxy = new OwnableDelegateProxy(user, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", user, address(this)));
proxies[user] = proxy;
return proxy;
}
/**
* Transfer access
*/
function transferAccessTo(address from, address to)
public
{
OwnableDelegateProxy proxy = proxies[from];
/* CHECKS */
require(OwnableDelegateProxy(msg.sender) == proxy, "Proxy transfer can only be called by the proxy");
require(proxies[to] == OwnableDelegateProxy(0), "Proxy transfer has existing proxy as destination");
/* EFFECTS */
delete proxies[from];
proxies[to] = proxy;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../registry/ProxyRegistry.sol";
import "../libraries/TransferHelper.sol";
import "./ERC20.sol";
contract TokenTransferProxy {
/* Authentication registry. */
ProxyRegistry public registry;
constructor(ProxyRegistry _registry)
{
require(address(_registry) != address(0), "INVALID REGISTRY");
registry = _registry;
}
/**
* Call ERC20 `transferFrom`
*
* @dev Authenticated contract only
* @param token ERC20 token address
* @param from From address
* @param to To address
* @param amount Transfer amount
*/
function transferFrom(address token, address from, address to, uint amount)
public
{
require(registry.contracts(msg.sender));
TransferHelper.safeTransferFrom(token, from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ERC20Basic.sol";
interface ERC20 is ERC20Basic {
function allowance(address owner, address spender)
external view returns (uint256);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ArrayUtils
* @author Wyvern Protocol Developers
*/
library ArrayUtils {
/**
* Replace bytes in an array with bytes in another array, guarded by a bitmask
* Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower)
* Modifies the provided byte array parameter in place
*
* @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed.
* @param array The original array
* @param desired The target array
* @param mask The mask specifying which bits can be changed
*/
function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask)
internal
pure
{
require(array.length == desired.length, "Arrays have different lengths");
require(array.length == mask.length, "Array and mask have different lengths");
uint words = array.length / 0x20;
uint index = words * 0x20;
assert(index / 0x20 == words);
uint i;
for (i = 0; i < words; i++) {
/* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
}
/* Deal with the last section of the byte array. */
if (words > 0) {
/* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */
i = words;
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
} else {
/* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise.
(bounds checks could still probably be optimized away in assembly, but this is a rare case) */
for (i = index; i < array.length; i++) {
array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]);
}
}
}
/**
* Test if two arrays are equal
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @dev Arrays must be of equal length, otherwise will return false
* @param a First array
* @param b Second array
* @return Whether or not all bytes in the arrays are equal
*/
function arrayEq(bytes memory a, bytes memory b)
internal
pure
returns (bool)
{
bool success = true;
assembly {
let length := mload(a)
// if lengths don't match the arrays are not equal
switch eq(length, mload(b))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(a, 0x20)
let end := add(mc, length)
for {
let cc := add(b, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
/**
* Drop the beginning of an array
*
* @param _bytes array
* @param _start start index
* @return Whether or not all bytes in the arrays are equal
*/
function arrayDrop(bytes memory _bytes, uint _start)
internal
pure
returns (bytes memory)
{
uint _length = SafeMath.sub(_bytes.length, _start);
return arraySlice(_bytes, _start, _length);
}
/**
* Take from the beginning of an array
*
* @param _bytes array
* @param _length elements to take
* @return Whether or not all bytes in the arrays are equal
*/
function arrayTake(bytes memory _bytes, uint _length)
internal
pure
returns (bytes memory)
{
return arraySlice(_bytes, 0, _length);
}
/**
* Slice an array
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @param _bytes array
* @param _start start index
* @param _length length to take
* @return Whether or not all bytes in the arrays are equal
*/
function arraySlice(bytes memory _bytes, uint _start, uint _length)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/**
* Unsafe write byte array into a memory location
*
* @param index Memory location
* @param source Byte array to write
* @return End memory index
*/
function unsafeWriteBytes(uint index, bytes memory source)
internal
pure
returns (uint)
{
if (source.length > 0) {
assembly {
let length := mload(source)
let end := add(source, add(0x20, length))
let arrIndex := add(source, 0x20)
let tempIndex := index
for { } eq(lt(arrIndex, end), 1) {
arrIndex := add(arrIndex, 0x20)
tempIndex := add(tempIndex, 0x20)
} {
mstore(tempIndex, mload(arrIndex))
}
index := add(index, length)
}
}
return index;
}
/**
* Unsafe write address into a memory location
*
* @param index Memory location
* @param source Address to write
* @return End memory index
*/
function unsafeWriteAddress(uint index, address source)
internal
pure
returns (uint)
{
uint conv = uint(source) << 0x60;
assembly {
mstore(index, conv)
index := add(index, 0x14)
}
return index;
}
/**
* Unsafe write uint into a memory location
*
* @param index Memory location
* @param source uint to write
* @return End memory index
*/
function unsafeWriteUint(uint index, uint source)
internal
pure
returns (uint)
{
assembly {
mstore(index, source)
index := add(index, 0x20)
}
return index;
}
/**
* Unsafe write uint8 into a memory location
*
* @param index Memory location
* @param source uint8 to write
* @return End memory index
*/
function unsafeWriteUint8(uint index, uint8 source)
internal
pure
returns (uint)
{
assembly {
mstore8(index, source)
index := add(index, 0x1)
}
return index;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
library SaleKindInterface {
/**
* Side: buy or sell.
*/
enum Side { Buy, Sell }
/**
* Currently supported kinds of sale: fixed price, Dutch auction.
* English auctions cannot be supported without stronger escrow guarantees.
* Future interesting options: Vickrey auction, nonlinear Dutch auctions.
*/
enum SaleKind { FixedPrice, DutchAuction }
/**
* @dev Check whether the parameters of a sale are valid
* @param saleKind Kind of sale
* @param expirationTime Order expiration time
* @return Whether the parameters were valid
*/
function validateParameters(SaleKind saleKind, uint expirationTime)
pure
internal
returns (bool)
{
/* Auctions must have a set expiration date. */
return (saleKind == SaleKind.FixedPrice || expirationTime > 0);
}
/**
* @dev Return whether or not an order can be settled
* @dev Precondition: parameters have passed validateParameters
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function canSettleOrder(uint listingTime, uint expirationTime)
view
internal
returns (bool)
{
return (listingTime < block.timestamp) && (expirationTime == 0 || block.timestamp < expirationTime);
}
/**
* @dev Calculate the settlement price of an order
* @dev Precondition: parameters have passed validateParameters.
* @param side Order side
* @param saleKind Method of sale
* @param basePrice Order base price
* @param extra Order extra price data
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime)
view
internal
returns (uint finalPrice)
{
if (saleKind == SaleKind.FixedPrice) {
return basePrice;
} else if (saleKind == SaleKind.DutchAuction) {
uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(block.timestamp, listingTime)), SafeMath.sub(expirationTime, listingTime));
if (side == Side.Sell) {
/* Sell-side - start price: basePrice. End price: basePrice - extra. */
return SafeMath.sub(basePrice, diff);
} else {
/* Buy-side - start price: basePrice. End price: basePrice + extra. */
return SafeMath.add(basePrice, diff);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title ReentrancyGuarded
* @author Wyvern Protocol Developers
*/
contract ReentrancyGuarded {
bool reentrancyLock = false;
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard {
require(!reentrancyLock, "Reentrancy detected");
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
/*
Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ProxyRegistry.sol";
import "./TokenRecipient.sol";
import "./proxy/OwnedUpgradeabilityStorage.sol";
/**
* @title AuthenticatedProxy
* @author Wyvern Protocol Developers
*/
contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage {
/* Whether initialized. */
bool initialized = false;
/* Address which owns this proxy. */
address public user;
/* Associated registry with contract authentication information. */
ProxyRegistry public registry;
/* Whether access has been revoked. */
bool public revoked;
/* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */
enum HowToCall { Call, DelegateCall }
/* Event fired when the proxy access is revoked or unrevoked. */
event Revoked(bool revoked);
/**
* Initialize an AuthenticatedProxy
*
* @param addrUser Address of user on whose behalf this proxy will act
* @param addrRegistry Address of ProxyRegistry contract which will manage this proxy
*/
function initialize (address addrUser, ProxyRegistry addrRegistry)
public
{
require(!initialized, "Authenticated proxy already initialized");
initialized = true;
user = addrUser;
registry = addrRegistry;
}
/**
* Set the revoked flag (allows a user to revoke ProxyRegistry access)
*
* @dev Can be called by the user only
* @param revoke Whether or not to revoke access
*/
function setRevoke(bool revoke)
public
{
require(msg.sender == user, "Authenticated proxy can only be revoked by its user");
revoked = revoke;
emit Revoked(revoke);
}
/**
* Execute a message call from the proxy contract
*
* @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access
* @param dest Address to which the call will be sent
* @param howToCall Which kind of call to make
* @param data Calldata to send
* @return result Result of the call (success or failure)
*/
function proxy(address dest, HowToCall howToCall, bytes memory data)
public
returns (bool result, bytes memory ret)
{
require(msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access");
if (howToCall == HowToCall.Call) {
(result, ret) = dest.call(data);
} else if (howToCall == HowToCall.DelegateCall) {
(result, ret) = dest.delegatecall(data);
}
}
/**
* Execute a message call and assert success
*
* @dev Same functionality as `proxy`, just asserts the return value
* @param dest Address to which the call will be sent
* @param howToCall What kind of call to make
* @param data Calldata to send
*/
function proxyAssert(address dest, HowToCall howToCall, bytes memory data)
public
{
(bool result, ) = proxy(dest, howToCall, data);
require(result, "Proxy assertion failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/LibPart.sol";
import "../royalties/RoyaltiesV2.sol";
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../libraries/ReentrancyGuarded.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/ERC20.sol";
import "../modules/TokenTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "../interfaces/IPaceArtStore.sol";
contract ExchangeCore is ReentrancyGuarded, Ownable {
address public defaultCollection;
/* The token used to pay exchange fees. */
ERC20 public exchangeToken;
/* User registry. */
ProxyRegistry public registry;
/* Token transfer proxy. */
TokenTransferProxy public tokenTransferProxy;
/* Cancelled / finalized orders, by hash. */
mapping(bytes32 => bool) public cancelledOrFinalized;
/* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */
mapping(bytes32 => bool) public approvedOrders;
// /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumMakerProtocolFee = 0;
// /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumTakerProtocolFee = 0;
// /* Recipient of protocol fees. */
// address public protocolFeeRecipient;
/* Fee method: protocol fee or split fee. */
enum FeeMethod { ProtocolFee, SplitFee }
/* Inverse basis point. */
uint public constant INVERSE_BASIS_POINT = 10000;
/* An ECDSA signature. */
struct Sig {
/* v parameter */
uint8 v;
/* r parameter */
bytes32 r;
/* s parameter */
bytes32 s;
}
/* An order on the exchange. */
struct Order {
/* Exchange address, intended as a versioning mechanism. */
address exchange;
/* Order maker address. */
address maker;
/* Order taker address, if specified. */
address taker;
/* Maker relayer fee of the order, unused for taker order. */
uint makerRelayerFee;
/* Taker relayer fee of the order, or maximum taker fee for a taker order. */
uint takerRelayerFee;
// /* Maker protocol fee of the order, unused for taker order. */
// uint makerProtocolFee;
// /* Taker protocol fee of the order, or maximum taker fee for a taker order. */
// uint takerProtocolFee;
/* Order fee recipient or zero address for taker order. */
address feeRecipient;
/* Fee method (protocol token or split fee). */
FeeMethod feeMethod;
/* Side (buy/sell). */
SaleKindInterface.Side side;
/* Kind of sale. */
SaleKindInterface.SaleKind saleKind;
/* Target. */
address target;
/* HowToCall. */
AuthenticatedProxy.HowToCall howToCall;
/* Calldata. */
bytes callData;
bytes replacementPattern;
/* Calldata replacement pattern, or an empty byte array for no replacement. */
// bytes replacementPattern;
// /* Static call target, zero-address for no static call. */
address staticTarget;
/* Static call extra data. */
bytes staticExtradata;
/* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
address paymentToken;
/* Base price of the order (in paymentTokens). */
uint basePrice;
/* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */
uint extra;
/* Listing timestamp. */
uint listingTime;
/* Expiration timestamp - 0 for no expiry. */
uint expirationTime;
/* Order salt, used to prevent duplicate hashes. */
uint salt;
}
event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
// event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
// event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
event OrderCancelled (bytes32 indexed hash);
event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata);
// /**
// * @dev Change the minimum maker fee paid to the protocol (owner only)
// * @param newMinimumMakerProtocolFee New fee to set in basis points
// */
// function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee)
// public
// onlyOwner
// {
// minimumMakerProtocolFee = newMinimumMakerProtocolFee;
// }
// /**
// * @dev Change the minimum taker fee paid to the protocol (owner only)
// * @param newMinimumTakerProtocolFee New fee to set in basis points
// */
// function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee)
// public
// onlyOwner
// {
// minimumTakerProtocolFee = newMinimumTakerProtocolFee;
// }
// /**
// * @dev Change the protocol fee recipient (owner only)
// * @param newProtocolFeeRecipient New protocol fee recipient address
// */
// function changeProtocolFeeRecipient(address newProtocolFeeRecipient)
// public
// onlyOwner
// {
// protocolFeeRecipient = newProtocolFeeRecipient;
// }
function changeDefaultCollection(address _newCollection) public onlyOwner {
require(_newCollection != defaultCollection, "PaceArtExchange::New collection address is the same");
defaultCollection = _newCollection;
}
/**
* @dev Transfer tokens
* @param token Token to transfer
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function transferTokens(address token, address from, address to, uint amount)
internal
{
if (amount > 0) {
tokenTransferProxy.transferFrom(token, from, to, amount);
}
}
/**
* @dev Charge a fee in protocol tokens
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function chargeProtocolFee(address from, address to, uint amount)
internal
{
transferTokens(address(exchangeToken), from, to, amount);
}
/**
* @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call)
* @param target Contract to call
* @param callData Calldata (appended to extradata)
* @param extradata Base data for STATICCALL (probably function selector and argument encoding)
*/
// function staticCall(address target, bytes memory callData, bytes memory extradata)
// public
// view
// returns (bool result)
// {
// bytes memory combined = new bytes(callData.length + extradata.length);
// uint index;
// assembly {
// index := add(combined, 0x20)
// }
// index = ArrayUtils.unsafeWriteBytes(index, extradata);
// ArrayUtils.unsafeWriteBytes(index, callData);
// assembly {
// result := staticcall(gas(), target, add(combined, 0x20), mload(combined), mload(0x40), 0)
// }
// return result;
// }
/**
* Calculate size of an order struct when tightly packed
*
* @param order Order to calculate size of
* @return Size in bytes
*/
function sizeOf(Order memory order)
internal
pure
returns (uint)
{
return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length);
// return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length);
}
/**
* @dev Hash an order, returning the canonical order hash, without the message prefix
* @param order Order to hash
*/
function hashOrder(Order memory order)
internal
pure
returns (bytes32 hash)
{
/* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
uint size = sizeOf(order);
bytes memory array = new bytes(size);
uint index;
assembly {
index := add(array, 0x20)
}
index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
index = ArrayUtils.unsafeWriteAddress(index, order.maker);
index = ArrayUtils.unsafeWriteAddress(index, order.taker);
index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee);
// index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee);
// index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee);
index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
index = ArrayUtils.unsafeWriteAddress(index, order.target);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall));
index = ArrayUtils.unsafeWriteBytes(index, order.callData);
index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern);
index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget);
index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata);
index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
index = ArrayUtils.unsafeWriteUint(index, order.extra);
index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
index = ArrayUtils.unsafeWriteUint(index, order.salt);
assembly {
hash := keccak256(add(array, 0x20), size)
}
return hash;
}
/**
* @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
* @param order Order to hash
* @return Hash of message prefix and order hash per Ethereum format
*/
function hashToSign(Order memory order)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
/**
* @dev Assert an order is valid and return its hash
* @param order Order to validate
* @param sig ECDSA signature
*/
function requireValidOrder(Order memory order, Sig memory sig)
internal
view
returns (bytes32)
{
bytes32 hash = hashToSign(order);
require(validateOrder(hash, order, sig), "INVALID_ORDER_HASH");
return hash;
}
/**
* @dev Validate order parameters (does *not* check signature validity)
* @param order Order to validate
*/
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
{
/* Order must be targeted at this protocol version (this Exchange contract). */
if (order.exchange != address(this)) {
return false;
}
/* Order must possess valid sale kind parameter combination. */
if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) {
return false;
}
// /* If using the split fee method, order must have sufficient protocol fees. */
// if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) {
// return false;
// }
return true;
}
/**
* @dev Validate a provided previously approved / signed order, hash, and signature.
* @param hash Order hash (already calculated, passed to avoid recalculation)
* @param order Order to validate
* @param sig ECDSA signature
*/
function validateOrder(bytes32 hash, Order memory order, Sig memory sig)
internal
view
returns (bool)
{
/* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */
/* Order must have valid parameters. */
if (!validateOrderParameters(order)) {
return false;
}
/* Order must have not been canceled or already filled. */
if (cancelledOrFinalized[hash]) {
return false;
}
/* Order authentication. Order must be either:
/* (a) previously approved */
if (approvedOrders[hash]) {
return true;
}
/* or (b) ECDSA-signed by maker. */
if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
return true;
}
return false;
}
/**
* @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order
* @param order Order to approve
* @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks
*/
function approveOrder(Order memory order, bool orderbookInclusionDesired)
internal
{
/* CHECKS */
/* Assert sender is authorized to approve order. */
require(msg.sender == order.maker);
/* Calculate order hash. */
bytes32 hash = hashToSign(order);
/* Assert order has not already been approved. */
require(!approvedOrders[hash]);
/* EFFECTS */
/* Mark order as approved. */
approvedOrders[hash] = true;
/* Log approval event. Must be split in two due to Solidity stack size limitations. */
{
emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target);
}
{
emit OrderApprovedPartTwo(hash, order.howToCall, order.callData, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired);
}
}
/**
* @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
{
/* CHECKS */
/* Calculate order hash. */
bytes32 hash = requireValidOrder(order, sig);
/* Assert sender is authorized to cancel order. */
require(msg.sender == order.maker);
/* Mark order as cancelled, preventing it from being matched. */
cancelledOrFinalized[hash] = true;
/* Log cancel event. */
emit OrderCancelled(hash);
}
/**
* @dev Calculate the current price of an order (convenience function)
* @param order Order to calculate the price of
* @return The current price of the order
*/
function calculateCurrentPrice (Order memory order)
internal
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime);
}
/**
* @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Match price
*/
function calculateMatchPrice(Order memory buy, Order memory sell)
view
internal
returns (uint)
{
/* Calculate sell price. */
uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime);
/* Calculate buy price. */
uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime);
/* Require price cross. */
require(buyPrice >= sellPrice);
/* Maker/taker priority. */
return sell.feeRecipient != address(0) ? sellPrice : buyPrice;
}
/**
* @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
* @param buy Buy-side order
* @param sell Sell-side order
*/
function executeFundsTransfer(Order memory buy, Order memory sell, LibPart.Part memory royalty)
internal
returns (uint)
{
/* Only payable in the special case of unwrapped Ether. */
if (sell.paymentToken != address(0)) {
require(msg.value == 0);
}
/* Calculate match price. */
uint price = calculateMatchPrice(buy, sell);
/* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */
if (price > 0 && sell.paymentToken != address(0)) {
transferTokens(sell.paymentToken, buy.maker, sell.maker, price);
}
/* Amount that will be received by seller (for Ether). */
uint receiveAmount = price;
/* Amount that must be sent by buyer (for Ether). */
uint requiredAmount = price;
/* Determine maker/taker and charge fees accordingly. */
if (sell.feeRecipient != address(0)) {
/* Sell-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by buyer. */
require(sell.takerRelayerFee <= buy.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
// /* Assert taker fee is less than or equal to maximum fee specified by buyer. */
// require(sell.takerProtocolFee <= buy.takerProtocolFee);
/* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */
if (sell.makerRelayerFee > 0) {
uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee);
payable(sell.feeRecipient).transfer(makerRelayerFee);
} else {
transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee);
}
}
if (sell.takerRelayerFee > 0) {
uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee);
payable(sell.feeRecipient).transfer(takerRelayerFee);
} else {
transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee);
}
}
// if (sell.makerProtocolFee > 0) {
// uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee);
// protocolFeeRecipient.transfer(makerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee);
// }
// }
// if (sell.takerProtocolFee > 0) {
// uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee);
// protocolFeeRecipient.transfer(takerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee);
// }
// }
} else {
/* Charge maker fee to seller. */
chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee);
/* Charge taker fee to buyer. */
chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee);
}
} else {
/* Buy-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by seller. */
require(buy.takerRelayerFee <= sell.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
/* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */
require(sell.paymentToken != address(0));
// /* Assert taker fee is less than or equal to maximum fee specified by seller. */
// require(buy.takerProtocolFee <= sell.takerProtocolFee);
if (buy.makerRelayerFee > 0) {
uint makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee);
}
if (buy.takerRelayerFee > 0) {
uint takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee);
}
// if (buy.makerProtocolFee > 0) {
// makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee);
// }
// if (buy.takerProtocolFee > 0) {
// takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee);
// }
} else {
/* Charge maker fee to buyer. */
chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee);
/* Charge taker fee to seller. */
chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee);
}
}
if (royalty.account != address(0) && royalty.value > 0) {
uint royaltyAmount = SafeMath.div(SafeMath.mul(royalty.value, price), INVERSE_BASIS_POINT);
receiveAmount = SafeMath.sub(receiveAmount, royaltyAmount);
if (sell.paymentToken == address(0)) {
royalty.account.transfer(royaltyAmount);
}
if (sell.paymentToken != address(0) && sell.maker != royalty.account) {
transferTokens(
sell.paymentToken,
sell.maker,
royalty.account,
royaltyAmount
);
}
}
if (sell.paymentToken == address(0)) {
/* Special-case Ether, order must be matched by buyer. */
require(msg.value >= requiredAmount);
payable(sell.maker).transfer(receiveAmount);
/* Allow overshoot for variable-price auctions, refund difference. */
uint diff = SafeMath.sub(msg.value, requiredAmount);
if (diff > 0) {
payable(buy.maker).transfer(diff);
}
}
/* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
return price;
}
/**
* @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Whether or not the two orders can be matched
*/
function ordersCanMatch(Order memory buy, Order memory sell)
internal
view
returns (bool)
{
return (
/* Must be opposite-side. */
(buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) &&
/* Must use same fee method. */
(buy.feeMethod == sell.feeMethod) &&
/* Must use same payment token. */
(buy.paymentToken == sell.paymentToken) &&
/* Must match maker/taker addresses. */
(sell.taker == address(0) || sell.taker == buy.maker) &&
(buy.taker == address(0) || buy.taker == sell.maker) &&
/* One must be maker and the other must be taker (no bool XOR in Solidity). */
((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) &&
/* Must match target. */
(buy.target == sell.target) &&
/* Must match howToCall. */
(buy.howToCall == sell.howToCall) &&
/* Buy-side order must be settleable. */
SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) &&
/* Sell-side order must be settleable. */
SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime)
);
}
function makeStaticCall(Order memory order, bool callMint) internal returns(bytes memory) {
if (callMint) {
require(
IPaceArtStore(order.target).owner() == order.maker || order.target == defaultCollection,
"PaceArtExchange::INVALID_COLLECTION"
);
(bool result, bytes memory returnData) = order.target.call(order.callData);
require(result, "Exchange::Failed when call other contract");
return returnData;
} else {
/* Retrieve delegateProxy contract. */
OwnableDelegateProxy delegateProxy = registry.proxies(order.maker);
/* Proxy must exist. */
require(address(delegateProxy) != address(0), "User not registed proxy yet!");
/* Assert implementation. */
require(delegateProxy.implementation() == registry.delegateProxyImplementation());
/* Execute specified call through proxy. */
(bool result, bytes memory returnData) = AuthenticatedProxy(address(delegateProxy)).proxy(order.target, order.howToCall, order.callData);
require(result, "Exchange::Failed when call other contract");
return returnData;
}
}
/**
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
* @param buy Buy-side order
* @param buySig Buy-side order signature
* @param sell Sell-side order
* @param sellSig Sell-side order signature
*/
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata)
internal
reentrancyGuard
{
/* CHECKS */
/* Ensure buy order validity and calculate hash if necessary. */
bytes32 buyHash;
if (buy.maker == msg.sender) {
require(validateOrderParameters(buy));
} else {
buyHash = requireValidOrder(buy, buySig);
}
/* Ensure sell order validity and calculate hash if necessary. */
bytes32 sellHash;
if (sell.maker == msg.sender) {
require(validateOrderParameters(sell));
} else {
sellHash = requireValidOrder(sell, sellSig);
}
/* Must be matchable. */
require(ordersCanMatch(buy, sell), "PaceArtExchange:: Order not matched");
/* Target must exist (prevent malicious selfdestructs just prior to order settlement). */
uint size;
address target = sell.target;
assembly {
size := extcodesize(target)
}
require(size > 0);
/* Must match calldata after replacement, if specified. */
if (buy.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buy.callData, sell.callData, buy.replacementPattern);
}
if (sell.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sell.callData, buy.callData, sell.replacementPattern);
}
require(ArrayUtils.arrayEq(buy.callData, sell.callData));
/* Mark previously signed or approved orders as finalized. */
if (msg.sender != buy.maker) {
cancelledOrFinalized[buyHash] = true;
}
if (msg.sender != sell.maker) {
cancelledOrFinalized[sellHash] = true;
}
bytes4 signature;
assembly {
let callData := mload(add(sell, mul(0x20, 11)))
signature := mload(add(callData, 0x20))
}
bytes memory returnData = makeStaticCall(sell, signature == 0xda22caf8);
// Transfer Royalty Fee. Prevent stack too deep errors
uint tokenId = abi.decode(returnData, (uint));
/* Execute funds transfer and pay fees. */
uint price = executeFundsTransfer(buy, sell, RoyaltiesV2(sell.target).getPaceArtV2Royalties(tokenId));
// }
/* Log match event. */
emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
/*
OwnableDelegateProxy
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./proxy/OwnedUpgradeabilityProxy.sol";
/**
* @title OwnableDelegateProxy
* @author Wyvern Protocol Developers
*/
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes memory data)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
(bool success,) = initialImplementation.delegatecall(data);
require(success, "OwnableDelegateProxy failed implementation");
}
}
/*
Proxy registry interface.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./OwnableDelegateProxy.sol";
/**
* @title ProxyRegistryInterface
* @author Wyvern Protocol Developers
*/
interface ProxyRegistryInterface {
function delegateProxyImplementation() external returns (address);
function proxies(address owner) external returns (OwnableDelegateProxy);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./Proxy.sol";
import "./OwnedUpgradeabilityStorage.sol";
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() override public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return proxyTypeId Proxy type, 2 for forwarding proxy
*/
function proxyType() override public pure returns (uint256 proxyTypeId) {
return 2;
}
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation, "Proxy already uses this implementation");
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "Only the proxy owner can call this method");
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "New owner cannot be the null address");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner {
upgradeTo(implementation);
(bool success,) = address(this).delegatecall(data);
require(success, "Call failed after proxy upgrade");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() virtual public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return proxyTypeId Type of proxy, 2 for upgradeable proxy
*/
function proxyType() virtual public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback () external payable {
address _impl = implementation();
require(_impl != address(0), "Proxy implementation required");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title OwnedUpgradeabilityStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface ERC20Basic {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/*
Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters).
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../modules/ERC20.sol";
/**
* @title TokenRecipient
* @author Wyvern Protocol Developers
*/
contract TokenRecipient {
event ReceivedEther(address indexed sender, uint amount);
event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData);
/**
* @dev Receive tokens and generate a log event
* @param from Address from which to transfer tokens
* @param value Amount of tokens to transfer
* @param token Address of token
* @param extraData Additional data to log
*/
function receiveApproval(address from, uint256 value, address token, bytes memory extraData) public {
ERC20 t = ERC20(token);
require(t.transferFrom(from, address(this), value), "ERC20 token transfer failed");
emit ReceivedTokens(from, value, token, extraData);
}
/**
* @dev Receive Ether and generate a log event
*/
fallback () payable external {
emit ReceivedEther(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT pragma
pragma solidity 0.7.5;
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32){
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part royalties);
function getPaceArtV2Royalties(uint256 id) external view returns (LibPart.Part memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface IPaceArtStore {
function singleTransfer(
address _from,
address _to,
uint256 _tokenId
) external returns(uint);
function mintTo(address _to, LibPart.Part memory _royalty) external returns(uint);
function owner() external view returns (address);
}
|
Hash an order, returning the hash that a client must sign, including the standard message prefix order Order to hash return Hash of message prefix and order hash per Ethereum format/
|
function hashToSign(Order memory order)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
| 12,646,976
|
./partial_match/1/0xb4eA9A0c1edD5C41585CD3715a1269b9dD3105A5/sources/contracts/royalties/Royalties.sol
|
CreatorCore bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 => 0xbb3bafd6 = 0xbb3bafd6/ Rarible: RoyaltiesV1 bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584/ Foundation bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c => 0xd5a06d4c = 0xd5a06d4c/ EIP-2981 bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a => 0x2a55205a = 0x2a55205a/ No delete necessary because the token will not have existed before this point
|
function _existsRoyalties(
uint256 tokenId
) internal view virtual returns (bool);
bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6;
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a;
function _setTokenRoyaltiesOnMint(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
_checkRoyalties(receivers, basisPoints);
_setRoyalties(receivers, basisPoints, _tokenRoyalties[tokenId]);
}
| 4,093,913
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
import "./ProtoBufRuntime.sol";
import "./GoogleProtobufAny.sol";
library NftTransfer {
//struct definition
struct Data {
string class;
string id;
string uri;
string sender;
string receiver;
bool awayFromOrigin;
string destContract;
}
// Decoder section
/**
* @dev The main decoder for memory
* @param bs The bytes array to be decoded
* @return The decoded struct
*/
function decode(bytes memory bs) internal pure returns (Data memory) {
(Data memory x, ) = _decode(32, bs, bs.length);
return x;
}
/**
* @dev The main decoder for storage
* @param self The in-storage struct
* @param bs The bytes array to be decoded
*/
function decode(Data storage self, bytes memory bs) internal {
(Data memory x, ) = _decode(32, bs, bs.length);
store(x, self);
}
// inner decoder
/**
* @dev The decoder for internal usage
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param sz The number of bytes expected
* @return The decoded struct
* @return The number of bytes decoded
*/
function _decode(uint256 p, bytes memory bs, uint256 sz)
internal
pure
returns (Data memory, uint)
{
Data memory r;
uint[8] memory counters;
uint256 fieldId;
ProtoBufRuntime.WireType wireType;
uint256 bytesRead;
uint256 offset = p;
uint256 pointer = p;
while (pointer < offset + sz) {
(fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs);
pointer += bytesRead;
if (fieldId == 1) {
pointer += _read_class(pointer, bs, r, counters);
}
else if (fieldId == 2) {
pointer += _read_id(pointer, bs, r, counters);
}
else if (fieldId == 3) {
pointer += _read_uri(pointer, bs, r, counters);
}
else if (fieldId == 4) {
pointer += _read_sender(pointer, bs, r, counters);
}
else if (fieldId == 5) {
pointer += _read_receiver(pointer, bs, r, counters);
}
else if (fieldId == 6) {
pointer += _read_awayFromOrigin(pointer, bs, r, counters);
}
else if (fieldId == 7) {
pointer += _read_destContract(pointer, bs, r, counters);
}
else {
if (wireType == ProtoBufRuntime.WireType.Fixed64) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed64(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Fixed32) {
uint256 size;
(, size) = ProtoBufRuntime._decode_fixed32(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.Varint) {
uint256 size;
(, size) = ProtoBufRuntime._decode_varint(pointer, bs);
pointer += size;
}
if (wireType == ProtoBufRuntime.WireType.LengthDelim) {
uint256 size;
(, size) = ProtoBufRuntime._decode_lendelim(pointer, bs);
pointer += size;
}
}
}
return (r, sz);
}
// field readers
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_class(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[1] += 1;
} else {
r.class = x;
if (counters[1] > 0) counters[1] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_id(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[2] += 1;
} else {
r.id = x;
if (counters[2] > 0) counters[2] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_uri(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[3] += 1;
} else {
r.uri = x;
if (counters[3] > 0) counters[3] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_sender(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[4] += 1;
} else {
r.sender = x;
if (counters[4] > 0) counters[4] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_receiver(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[5] += 1;
} else {
r.receiver = x;
if (counters[5] > 0) counters[5] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_awayFromOrigin(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(bool x, uint256 sz) = ProtoBufRuntime._decode_bool(p, bs);
if (isNil(r)) {
counters[6] += 1;
} else {
r.awayFromOrigin = x;
if (counters[6] > 0) counters[6] -= 1;
}
return sz;
}
/**
* @dev The decoder for reading a field
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @param r The in-memory struct
* @param counters The counters for repeated fields
* @return The number of bytes decoded
*/
function _read_destContract(
uint256 p,
bytes memory bs,
Data memory r,
uint[8] memory counters
) internal pure returns (uint) {
/**
* if `r` is NULL, then only counting the number of fields.
*/
(string memory x, uint256 sz) = ProtoBufRuntime._decode_string(p, bs);
if (isNil(r)) {
counters[7] += 1;
} else {
r.destContract = x;
if (counters[7] > 0) counters[7] -= 1;
}
return sz;
}
// Encoder section
/**
* @dev The main encoder for memory
* @param r The struct to be encoded
* @return The encoded byte array
*/
function encode(Data memory r) internal pure returns (bytes memory) {
bytes memory bs = new bytes(_estimate(r));
uint256 sz = _encode(r, 32, bs);
assembly {
mstore(bs, sz)
}
return bs;
}
// inner encoder
/**
* @dev The encoder for internal usage
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
uint256 offset = p;
uint256 pointer = p;
if (bytes(r.class).length != 0) {
pointer += ProtoBufRuntime._encode_key(
1,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.class, pointer, bs);
}
if (bytes(r.id).length != 0) {
pointer += ProtoBufRuntime._encode_key(
2,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.id, pointer, bs);
}
if (bytes(r.uri).length != 0) {
pointer += ProtoBufRuntime._encode_key(
3,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.uri, pointer, bs);
}
if (bytes(r.sender).length != 0) {
pointer += ProtoBufRuntime._encode_key(
4,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.sender, pointer, bs);
}
if (bytes(r.receiver).length != 0) {
pointer += ProtoBufRuntime._encode_key(
5,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.receiver, pointer, bs);
}
if (r.awayFromOrigin != false) {
pointer += ProtoBufRuntime._encode_key(
6,
ProtoBufRuntime.WireType.Varint,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_bool(r.awayFromOrigin, pointer, bs);
}
if (bytes(r.destContract).length != 0) {
pointer += ProtoBufRuntime._encode_key(
7,
ProtoBufRuntime.WireType.LengthDelim,
pointer,
bs
);
pointer += ProtoBufRuntime._encode_string(r.destContract, pointer, bs);
}
return pointer - offset;
}
// nested encoder
/**
* @dev The encoder for inner struct
* @param r The struct to be encoded
* @param p The offset of bytes array to start decode
* @param bs The bytes array to be decoded
* @return The number of bytes encoded
*/
function _encode_nested(Data memory r, uint256 p, bytes memory bs)
internal
pure
returns (uint)
{
/**
* First encoded `r` into a temporary array, and encode the actual size used.
* Then copy the temporary array into `bs`.
*/
uint256 offset = p;
uint256 pointer = p;
bytes memory tmp = new bytes(_estimate(r));
uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp);
uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs);
uint256 size = _encode(r, 32, tmp);
pointer += ProtoBufRuntime._encode_varint(size, pointer, bs);
ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size);
pointer += size;
delete tmp;
return pointer - offset;
}
// estimator
/**
* @dev The estimator for a struct
* @param r The struct to be encoded
* @return The number of bytes encoded in estimation
*/
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.class).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.id).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.uri).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.sender).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.receiver).length);
e += 1 + 1;
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.destContract).length);
return e;
}
// empty checker
function _empty(
Data memory r
) internal pure returns (bool) {
if (bytes(r.class).length != 0) {
return false;
}
if (bytes(r.id).length != 0) {
return false;
}
if (bytes(r.uri).length != 0) {
return false;
}
if (bytes(r.sender).length != 0) {
return false;
}
if (bytes(r.receiver).length != 0) {
return false;
}
if (r.awayFromOrigin != false) {
return false;
}
if (bytes(r.destContract).length != 0) {
return false;
}
return true;
}
//store function
/**
* @dev Store in-memory struct to storage
* @param input The in-memory struct
* @param output The in-storage struct
*/
function store(Data memory input, Data storage output) internal {
output.class = input.class;
output.id = input.id;
output.uri = input.uri;
output.sender = input.sender;
output.receiver = input.receiver;
output.awayFromOrigin = input.awayFromOrigin;
output.destContract = input.destContract;
}
//utility functions
/**
* @dev Return an empty struct
* @return r The empty struct
*/
function nil() internal pure returns (Data memory r) {
assembly {
r := 0
}
}
/**
* @dev Test whether a struct is empty
* @param x The struct to be tested
* @return r True if it is empty
*/
function isNil(Data memory x) internal pure returns (bool r) {
assembly {
r := iszero(x)
}
}
}
//library NftTransfer
|
The estimator for a struct r The struct to be encoded return The number of bytes encoded in estimation/
|
function _estimate(
Data memory r
) internal pure returns (uint) {
uint256 e;
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.class).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.id).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.uri).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.sender).length);
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.receiver).length);
e += 1 + 1;
e += 1 + ProtoBufRuntime._sz_lendelim(bytes(r.destContract).length);
return e;
}
| 14,019,351
|
/**
* @title CryptoSpatialFeature
* @author BENAHMED DAHO Ali
* @notice an abstract contract that implement a Spatial Feature Geometry
* on the etherurm blockchain
*
* @dev GM_Primitive (ISO 19107)
*
* TODO :
* - make this contract Ownable
*
*/
pragma solidity ^0.5.0;
import './CSGeometryLib.sol';
import './CSFeatureInterface.sol';
import '@openzeppelin/contracts/access/Roles.sol';
import '@openzeppelin/contracts/ownership/Ownable.sol';
contract CSFeature is CSFeatureInterface, Ownable {
//
// State variables
//
bytes32 internal csc; // Crypto-Spatial Coordinate
bytes32 internal wkbHash; // Well Known Binary Hash
bytes15 internal dggsIndex; // DGGS (Disrcete Global Geodetic System) index
uint internal h3Resolution; // H3 resolution (H3 is a compliant DGGS library)
CSGeometryLib.CSGeometryType internal geomteryType; // geometry type
// adding access control
using Roles for Roles.Role;
Roles.Role private _admins;
//
// Events - publicize actions to external listeners
//
event LogFeatureCreated(bytes32 indexed csc, bytes15 indexed dggsIndex, bytes32 wkbHash, address indexed owner);
event LogFeatureKilled(bytes32 indexed csc, bytes15 indexed dggsIndex, bytes32 wkbHash, address indexed owner);
//
// Modifiers
//
modifier onlyAdmins(address _address) {
require(_admins.has(_address),"Caller haven't admins rights on the feature");
_;
}
//
// Functions
//
/**
* @notice constuctor
* @dev initialize state variables
*
*/
constructor (bytes15 _dggsIndex, bytes32 _wkbHash, address __owner, uint _h3Resolution) public Ownable() {
require((_h3Resolution >= 0 && _h3Resolution < 16), "H3 Resolution must be _h3Resolution >=0 && _h3Resolution <16");
require(_dggsIndex[0] != 0, "Empty dggsIndex");
require(_wkbHash[0] != 0, "Empty wkbHash");
transferOwnership(__owner);
_admins.add(__owner);
_admins.add(msg.sender);
wkbHash = _wkbHash;
dggsIndex = _dggsIndex;
geomteryType = CSGeometryLib.CSGeometryType.GM_POINT;
h3Resolution = _h3Resolution;
csc = CSGeometryLib.computeCSCIndex(__owner, _dggsIndex);
emit LogFeatureCreated(csc, dggsIndex, wkbHash, owner());
}
/**
* @dev getGeometryType
*/
function getGeometryType() external returns (CSGeometryLib.CSGeometryType) {
return geomteryType;
}
/**
*/
function getFeatureCSC() external view returns (bytes32) {
return (csc);
}
/**
*/
function getFeatureDGGSIndex() external view returns (bytes15) {
return (dggsIndex);
}
/**
* @dev returns all the values of the feature
*/
function fetchFeature() external view
returns (bytes32 _csc, bytes15 _dggsIndex, bytes32 _wkbHash, address __owner, uint _h3Resolution,
CSGeometryLib.CSGeometryType _geomteryType) {
return (csc,dggsIndex, wkbHash, owner(), h3Resolution, geomteryType);
}
/**
* @dev update the Well Known Binary Hash of the feature
*/
function setWkbHash(bytes32 _wkbHash) external
onlyAdmins(msg.sender)
returns (bytes32 _wkbHashValue) {
require(_wkbHash[0] != 0, "Empty wkbHash");
wkbHash = _wkbHash;
return _wkbHash;
}
/**
* @dev isAdmin : check if the addres is an admin of this feature
*
*/
function isAdmin(address _address) external view returns (bool) {
return _admins.has(_address);
}
/**
* @dev remove permanently the feature from the blockchain
* TODO cross check with Registry removeFeature
*/
function kill() external onlyAdmins(msg.sender) {
selfdestruct(address(uint160(owner()))); // cast owner to address payable
// TODO check if state variables values stay accessible after selfdestruct
emit LogFeatureKilled(csc, dggsIndex, wkbHash, owner());
}
/**
* @dev callback function
*/
function () external {
revert("this contract should never have a balance");
}
}
|
update the Well Known Binary Hash of the feature/
|
function setWkbHash(bytes32 _wkbHash) external
onlyAdmins(msg.sender)
returns (bytes32 _wkbHashValue) {
require(_wkbHash[0] != 0, "Empty wkbHash");
wkbHash = _wkbHash;
return _wkbHash;
}
| 2,574,660
|
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
/**
* @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees.
* @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its
* children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf
* node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a
* checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow
* accessing historic information.
*
* Example of a checkpointed binary sum tree:
*
* CURRENT PREVIOUS
*
* Level 2 100 ---------------------------------------- 70
* ______|_______ ______|_______
* / \ / \
* Level 1 34 66 ------------------------- 23 47
* _____|_____ _____|_____ _____|_____ _____|_____
* / \ / \ / \ / \
* Level 0 22 12 53 13 ----------- 22 1 17 30
*
*/
library HexSumTree {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW";
string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST";
string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS";
string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES";
// Constants used to perform tree computations
// To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN
// The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64)
uint256 private constant CHILDREN = 16;
uint256 private constant BITS_IN_NIBBLE = 4;
// All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree.
uint256 private constant ITEMS_LEVEL = 0;
// Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys
// starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys
// are computed based on their level and their children keys.
uint256 private constant BASE_KEY = 0;
// Timestamp used to checkpoint the first value of the tree height during initialization
uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0);
/**
* @dev The tree is stored using the following structure:
* - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value).
* - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children.
* - nextKey: The next key to be used to identify the next new value that will be inserted into the tree.
*/
struct Tree {
uint256 nextKey;
Checkpointing.History height;
mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes;
}
/**
* @dev Search params to traverse the tree caching previous results:
* - time: Point in time to query the values being searched, this value shouldn't change during a search
* - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves
* - parentKey: Key of the parent of the nodes being analyzed at the given level for the search
* - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list
* - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total
*/
struct SearchParams {
uint64 time;
uint256 level;
uint256 parentKey;
uint256 foundValues;
uint256 visitedTotal;
}
/**
* @dev Initialize tree setting the next key and first height checkpoint
*/
function init(Tree storage self) internal {
self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1);
self.nextKey = BASE_KEY;
}
/**
* @dev Insert a new item to the tree at given point in time
* @param _time Point in time to register the given value
* @param _value New numeric value to be added to the tree
* @return Unique key identifying the new value inserted
*/
function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) {
// As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be
// always incrementing, starting from zero. Add a new level if necessary.
uint256 key = self.nextKey++;
_addLevelIfNecessary(self, key, _time);
// If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of
// the tree if necessary, and finally update sums cached in all the non-leaf nodes.
if (_value > 0) {
_add(self, ITEMS_LEVEL, key, _time, _value);
_updateSums(self, key, _time, _value, true);
}
return key;
}
/**
* @dev Set the value of a leaf node indexed by its key at given point in time
* @param _time Point in time to set the given value
* @param _key Key of the leaf node to be set in the tree
* @param _value New numeric value to be set for the given key
*/
function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Set the new value for the requested leaf node
uint256 lastValue = getItem(self, _key);
_add(self, ITEMS_LEVEL, _key, _time, _value);
// Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update.
if (_value > lastValue) {
_updateSums(self, _key, _time, _value - lastValue, true);
} else if (_value < lastValue) {
_updateSums(self, _key, _time, lastValue - _value, false);
}
}
/**
* @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta
* @param _key Key of the leaf node to be updated in the tree
* @param _time Point in time to update the given value
* @param _delta Numeric delta to update the value of the given key
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value
*/
function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Update the value of the requested leaf node based on the given delta
uint256 lastValue = getItem(self, _key);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, ITEMS_LEVEL, _key, _time, newValue);
// Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update.
_updateSums(self, _key, _time, _delta, _positive);
}
/**
* @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest
* high value in case a value cannot be found. This function assumes the given list of given values to be
* searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results.
* @param _values Ordered list of values to be searched in the tree
* @param _time Point in time to query the values being searched
* @return keys List of keys found for each requested value in the same order
* @return values List of node values found for each requested value in the same order
*/
function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view
returns (uint256[] memory keys, uint256[] memory values)
{
require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES);
// Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total
uint256 total = getRecentTotalAt(self, _time);
// No need for SafeMath: positive length of array already checked
require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS);
// Build search params for the first iteration
uint256 rootLevel = getRecentHeightAt(self, _time);
SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0);
// These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies
uint256 length = _values.length;
keys = new uint256[](length);
values = new uint256[](length);
_search(self, _values, searchParams, keys, values);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree
*/
function getTotal(Tree storage self) internal view returns (uint256) {
uint256 rootLevel = getHeight(self);
return getNode(self, rootLevel, BASE_KEY);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a binary search for the root node, a linear one for the height.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getRecentNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key
* @param _key Key of the leaf node querying the value of
*/
function getItem(Tree storage self, uint256 _key) internal view returns (uint256) {
return getNode(self, ITEMS_LEVEL, _key);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key at a given point in time
* It uses a binary search.
* @param _key Key of the leaf node querying the value of
* @param _time Point in time to query the value of the requested leaf
*/
function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) {
return getNodeAt(self, ITEMS_LEVEL, _key, _time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
*/
function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) {
return self.nodes[_level][_key].getLast();
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a binary search.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].get(_time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a linear search starting from the end.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].getRecent(_time);
}
/**
* @dev Tell the height of the tree
*/
function getHeight(Tree storage self) internal view returns (uint256) {
return self.height.getLast();
}
/**
* @dev Tell the height of the tree at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the height of the tree
*/
function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) {
return self.height.getRecent(_time);
}
/**
* @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated
* @param _key Key of the leaf node to update the ancestors of
* @param _time Point in time to update the ancestors' values of the given leaf node
* @param _delta Numeric delta to update the ancestors' values of the given leaf node
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values
*/
function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private {
uint256 mask = uint256(-1);
uint256 ancestorKey = _key;
uint256 currentHeight = getHeight(self);
for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) {
// Build a mask to get the key of the ancestor at a certain level. For example:
// Level 0: leaves don't have children
// Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves)
// Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves)
// ...
// Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height)
mask = mask << BITS_IN_NIBBLE;
// The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles
// of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a
// certain level applying the mask to the ancestor's key of the previous level. Note that for the first
// iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated.
ancestorKey = ancestorKey & mask;
// Update value
uint256 lastValue = getNode(self, level, ancestorKey);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, level, ancestorKey, _time, newValue);
}
// Check if there was an overflow. Note that we only need to check the value stored in the root since the
// sum only increases going up through the tree.
require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW);
}
/**
* @dev Private function to add a new level to the tree based on a new key that will be inserted
* @param _newKey New key willing to be inserted in the tree
* @param _time Point in time when the new key will be inserted
*/
function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private {
uint256 currentHeight = getHeight(self);
if (_shouldAddLevel(currentHeight, _newKey)) {
// Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we
// are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of
// this system having 2^256 items inserted is unrealistic.
uint256 newHeight = currentHeight + 1;
uint256 rootValue = getNode(self, currentHeight, BASE_KEY);
_add(self, newHeight, BASE_KEY, _time, rootValue);
self.height.add(_time, newHeight);
}
}
/**
* @dev Private function to register a new value in the history of a node at a given point in time
* @param _level Level of the node to add a new value at a given point in time to
* @param _key Key of the node to add a new value at a given point in time to
* @param _time Point in time to register a value for the given node
* @param _value Numeric value to be registered for the given node at a given point in time
*/
function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private {
self.nodes[_level][_key].add(_time, _value);
}
/**
* @dev Recursive pre-order traversal function
* Every time it checks a node, it traverses the input array to find the initial subset of elements that are
* below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always
* the same, to avoid making extra copies, it just passes the number of values already found , to avoid
* checking values that went through a different branch. The same happens with the result lists of keys and
* values, these are the same on every recursion step. The visited total is carried over each iteration to
* avoid having to subtract all elements in the array.
* @param _values Ordered list of values to be searched in the tree
* @param _params Search parameters for the current recursive step
* @param _resultKeys List of keys found for each requested value in the same order
* @param _resultValues List of node values found for each requested value in the same order
*/
function _search(
Tree storage self,
uint256[] memory _values,
SearchParams memory _params,
uint256[] memory _resultKeys,
uint256[] memory _resultValues
)
private
view
{
uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE);
for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) {
// Return if we already found enough values
if (_params.foundValues >= _values.length) {
break;
}
// Build child node key shifting the child number to the position of the less significant nibble of
// the keys for the level being analyzed, and adding it to the key of the parent node. For example,
// for a tree with height 5, if we are checking the children of the second node of the level 3, whose
// key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are:
// Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000
// Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100
// Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200
// ...
// Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00
uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble);
uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time);
// Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous
// subset starting from the beginning, so we only need to know the length of that subset.
uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue);
uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal);
// If there are some values included in the subtree of the child node, visit them
if (subtreeIncludedValues > 0) {
// If the child node being analyzed is a leaf, add it to the list of results a number of times equals
// to the number of values that were included in it. Otherwise, descend one level.
if (_params.level == ITEMS_LEVEL) {
_copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues);
} else {
SearchParams memory nextLevelParams = SearchParams(
_params.time,
_params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero
childNodeKey,
_params.foundValues,
_params.visitedTotal
);
_search(self, _values, nextLevelParams, _resultKeys, _resultValues);
}
// Update the number of values that were already found
_params.foundValues = _params.foundValues.add(subtreeIncludedValues);
}
// Update the visited total for the next node in this level
_params.visitedTotal = newVisitedTotal;
}
}
/**
* @dev Private function to check if a new key can be added to the tree based on the current height of the tree
* @param _currentHeight Current height of the tree to check if it supports adding the given key
* @param _newKey Key willing to be added to the tree with the given current height
* @return True if the current height of the tree should be increased to add the new key, false otherwise.
*/
function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) {
// Build a mask that will match all the possible keys for the given height. For example:
// Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys)
// Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys)
// ...
// Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height)
uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE);
uint256 mask = uint256(-1) << shift;
// Check if the given key can be represented in the tree with the current given height using the mask.
return (_newKey & mask) != 0;
}
/**
* @dev Private function to tell how many values of a list can be found in a subtree
* @param _values List of values being searched in ascending order
* @param _foundValues Number of values that were already found and should be ignore
* @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it
* @return Number of values in the list that are included in the given subtree
*/
function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) {
// Look for all the values that can be found in the given subtree
uint256 i = _foundValues;
while (i < _values.length && _values[i] < _subtreeTotal) {
i++;
}
return i - _foundValues;
}
/**
* @dev Private function to copy a node a given number of times to a results list. This function assumes the given
* results list have enough size to support the requested copy.
* @param _from Index of the results list to start copying the given node
* @param _times Number of times the given node will be copied
* @param _key Key of the node to be copied
* @param _resultKeys Lists of key results to copy the given node key to
* @param _value Value of the node to be copied
* @param _resultValues Lists of value results to copy the given node value to
*/
function _copyFoundNode(
uint256 _from,
uint256 _times,
uint256 _key,
uint256[] memory _resultKeys,
uint256 _value,
uint256[] memory _resultValues
)
private
pure
{
for (uint256 i = 0; i < _times; i++) {
_resultKeys[_from + i] = _key;
_resultValues[_from + i] = _value;
}
}
}
/**
* @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree`
*/
library GuardiansTreeSortition {
using SafeMath for uint256;
using HexSumTree for HexSumTree.Tree;
string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH";
string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH";
/**
* @dev Search random items in the tree based on certain restrictions
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for
* @param _termId Current term when the draft is being computed
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @param _sortitionIteration Number of sortitions already performed for the given draft
* @return guardiansIds List of guardian ids obtained based on the requested search
* @return guardiansBalances List of active balances for each guardian obtained based on the requested search
*/
function batchedRandomSearch(
HexSumTree.Tree storage tree,
bytes32 _termRandomness,
uint256 _disputeId,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians,
uint256 _sortitionIteration
)
internal
view
returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances)
{
(uint256 low, uint256 high) = getSearchBatchBounds(
tree,
_termId,
_selectedGuardians,
_batchRequestedGuardians,
_roundRequestedGuardians
);
uint256[] memory balances = _computeSearchRandomBalances(
_termRandomness,
_disputeId,
_sortitionIteration,
_batchRequestedGuardians,
low,
high
);
(guardiansIds, guardiansBalances) = tree.search(balances, _termId);
require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH);
require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH);
}
/**
* @dev Get the bounds for a draft batch based on the active balances of the guardians
* @param _termId Term ID of the active balances that will be used to compute the boundaries
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch
* @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch
*/
function getSearchBatchBounds(
HexSumTree.Tree storage tree,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians
)
internal
view
returns (uint256 low, uint256 high)
{
uint256 totalActiveBalance = tree.getRecentTotalAt(_termId);
low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians);
high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
}
/**
* @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for (for randomness)
* @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness)
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians
* @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians
* @return Random list of active balances to be searched in the guardians tree for the given draft batch
*/
function _computeSearchRandomBalances(
bytes32 _termRandomness,
uint256 _disputeId,
uint256 _sortitionIteration,
uint256 _batchRequestedGuardians,
uint256 _lowBatchBound,
uint256 _highBatchBound
)
internal
pure
returns (uint256[] memory)
{
// Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the
// random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10).
require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH);
uint256 interval = _highBatchBound - _lowBatchBound;
// Compute an ordered list of random active balance to be searched in the guardians tree
uint256[] memory balances = new uint256[](_batchRequestedGuardians);
for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) {
// Compute a random seed using:
// - The inherent randomness associated to the term from blockhash
// - The disputeId, so 2 disputes in the same term will have different outcomes
// - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance
// - The guardian number in this batch
bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber));
// Compute a random active balance to be searched in the guardians tree using the generated seed within the
// boundaries computed for the current batch.
balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval);
// Make sure it's ordered, flip values if necessary
for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) {
uint256 tmp = balances[i - 1];
balances[i - 1] = balances[i];
balances[i] = tmp;
}
}
return balances;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ILockManager {
/**
* @dev Tell whether a user can unlock a certain amount of tokens
*/
function canUnlock(address user, uint256 amount) external view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using PctHelpers for uint256;
using HexSumTree for HexSumTree.Tree;
using GuardiansTreeSortition for HexSumTree.Tree;
string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT";
string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT";
string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT";
string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT";
string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN";
string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN";
string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN";
string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE";
string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED";
string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED";
string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT";
string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED";
string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK";
string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION";
string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION";
string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT";
string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED";
string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK";
// Address that will be used to burn guardian tokens
address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD);
// Maximum number of sortition iterations allowed per draft call
uint256 internal constant MAX_DRAFT_ITERATIONS = 10;
// "ERC20-lite" interface to provide help for tooling
string public constant name = "Court Staked Aragon Network Token";
string public constant symbol = "sANT";
uint8 public constant decimals = 18;
/**
* @dev Guardians have three kind of balances, these are:
* - active: tokens activated for the Court that can be locked in case the guardian is drafted
* - locked: amount of active tokens that are locked for a draft
* - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time
*
* Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others
* are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians'
* active balances cannot be affected during the current Court term, if guardians want to deactivate some of
* their active tokens, their balance will be updated for the following term, and they won't be allowed to
* withdraw them until the current term has ended.
*
* Note that even though guardians balances are stored separately, all the balances are held by this contract.
*/
struct Guardian {
uint256 id; // Key in the guardians tree used for drafting
uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts
uint256 availableBalance; // Available tokens that can be withdrawn at any time
uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked
ActivationLocks activationLocks; // Guardian's activation locks
DeactivationRequest deactivationRequest; // Guardian's pending deactivation request
}
/**
* @dev Guardians can define lock managers to control their minimum active balance in the registry
*/
struct ActivationLocks {
uint256 total; // Total amount of active balance locked
mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager
}
/**
* @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some
* of their tokens, the tree will always be updated for the following term, and they won't be able to
* withdraw the requested amount until the current term has finished. Thus, we need to keep track the term
* when a token deactivation was requested and its corresponding amount.
*/
struct DeactivationRequest {
uint256 amount; // Amount requested for deactivation
uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens
}
/**
* @dev Internal struct to wrap all the params required to perform guardians drafting
*/
struct DraftParams {
bytes32 termRandomness; // Randomness seed to be used for the draft
uint256 disputeId; // ID of the dispute being drafted
uint64 termId; // Term ID of the dispute's draft term
uint256 selectedGuardians; // Number of guardians already selected for the draft
uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft
uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted
uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian
uint256 iteration; // Sortition iteration number
}
// Maximum amount of total active balance that can be held in the registry
uint256 public totalActiveBalanceLimit;
// Guardian ERC20 token
IERC20 public guardiansToken;
// Mapping of guardian data indexed by address
mapping (address => Guardian) internal guardiansByAddress;
// Mapping of guardian addresses indexed by id
mapping (uint256 => address) internal guardiansAddressById;
// Tree to store guardians active balance by term for the drafting process
HexSumTree.Tree internal tree;
event Staked(address indexed guardian, uint256 amount, uint256 total);
event Unstaked(address indexed guardian, uint256 amount, uint256 total);
event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount);
event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount);
event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId);
event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId);
event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total);
event GuardianBalanceLocked(address indexed guardian, uint256 amount);
event GuardianBalanceUnlocked(address indexed guardian, uint256 amount);
event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event GuardianTokensAssigned(address indexed guardian, uint256 amount);
event GuardianTokensBurned(uint256 amount);
event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit);
/**
* @dev Constructor function
* @param _controller Address of the controller
* @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry
* @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry
*/
constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public {
require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT);
guardiansToken = _guardiansToken;
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
tree.init();
// First tree item is an empty guardian
assert(tree.insert(0, 0) == 0);
}
/**
* @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian to stake tokens to
* @param _amount Amount of tokens to be staked
*/
function stake(address _guardian, uint256 _amount) external {
_stake(_guardian, _amount);
}
/**
* @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian`
* @param _guardian Address of the guardian to unstake tokens from
* @param _amount Amount of tokens to be unstaked
*/
function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_unstake(_guardian, _amount);
}
/**
* @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian activating the tokens for
* @param _amount Amount of guardian tokens to be activated for the next term
*/
function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_activate(_guardian, _amount);
}
/**
* @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian deactivating the tokens for
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_deactivate(_guardian, _amount);
}
/**
* @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian staking and activating tokens for
* @param _amount Amount of tokens to be staked and activated
*/
function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_stake(_guardian, _amount);
_activate(_guardian, _amount);
}
/**
* @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian locking the activation for
* @param _lockManager Address of the lock manager that will control the lock
* @param _amount Amount of active tokens to be locked
*/
function lockActivation(address _guardian, address _lockManager, uint256 _amount) external {
// Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself
bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian);
// Make sure that the given lock manager is allowed
require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED);
_lockActivation(_guardian, _lockManager, _amount);
}
/**
* @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian unlocking the active balance of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of active tokens to be unlocked
* @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately
*/
function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 lockedAmount = activationLocks.lockedBy[_lockManager];
require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION);
uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount;
require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT);
// Always allow the lock manager to unlock
bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock);
require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION);
uint256 newLockedAmount = lockedAmount.sub(amountToUnlock);
uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
// In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it
if (_requestDeactivation) {
_authenticateSender(_guardian);
_deactivate(_guardian, _amount);
}
}
/**
* @notice Process a token deactivation requested for `_guardian` if there is any
* @param _guardian Address of the guardian to process the deactivation request of
*/
function processDeactivationRequest(address _guardian) external {
uint64 termId = _ensureCurrentTerm();
_processDeactivationRequest(_guardian, termId);
}
/**
* @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian`
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(_guardian, _amount, true);
emit GuardianTokensAssigned(_guardian, _amount);
}
}
/**
* @notice Burn `@tokenAmount(self.token(), _amount)`
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true);
emit GuardianTokensBurned(_amount);
}
}
/**
* @notice Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) {
DraftParams memory draftParams = _buildDraftParams(_params);
guardians = new address[](draftParams.batchRequestedGuardians);
// Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus,
// we compute several sortitions until all the requested guardians are selected. To guarantee a different set of
// guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition.
// Note that we are capping the number of iterations to avoid an OOG error, which means that this function could
// return less guardians than the requested number.
for (draftParams.iteration = 0;
length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS;
draftParams.iteration++
) {
(uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams);
for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) {
// We assume the selected guardians are registered in the registry, we are not checking their addresses exist
address guardianAddress = guardiansAddressById[guardianIds[i]];
Guardian storage guardian = guardiansByAddress[guardianAddress];
// Compute new locked balance for a guardian based on the penalty applied when being drafted
uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount);
// Check if there is any deactivation requests for the next term. Drafts are always computed for the current term
// but we have to make sure we are locking an amount that will exist in the next term.
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1);
// Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise.
uint256 currentActiveBalance = activeBalances[i];
if (currentActiveBalance >= newLockedBalance) {
// Check if the amount of active tokens for the next term is enough to lock the required amount for
// the draft. Otherwise, reduce the requested deactivation amount of the next term.
// Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath
uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount);
if (nextTermActiveBalance < newLockedBalance) {
// No need for SafeMath: we already checked values above
_reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId);
}
// Update the current active locked balance of the guardian
guardian.lockedBalance = newLockedBalance;
guardians[length++] = guardianAddress;
emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount);
}
}
}
}
/**
* @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the
* corresponding locked balances of those guardians that are set to be slashed.
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
onlyActiveDisputeManager
returns (uint256)
{
require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH);
require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH);
uint64 nextTermId = _termId + 1;
uint256 collectedTokens;
for (uint256 i = 0; i < _guardians.length; i++) {
uint256 lockedAmount = _lockedAmounts[i];
address guardianAddress = _guardians[i];
Guardian storage guardian = guardiansByAddress[guardianAddress];
guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount);
// Slash guardian if requested. Note that there's no need to check if there was a deactivation
// request since we're working with already locked balances.
if (_rewardedGuardians[i]) {
emit GuardianBalanceUnlocked(guardianAddress, lockedAmount);
} else {
collectedTokens = collectedTokens.add(lockedAmount);
tree.update(guardian.id, nextTermId, lockedAmount, false);
emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId);
}
}
return collectedTokens;
}
/**
* @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`.
* @dev This function tries to decrease the active balance of a guardian for the next term based on the requested
* amount. It can be seen as a way to early-slash a guardian's active balance.
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) {
if (_amount == 0) {
return true;
}
uint64 nextTermId = _termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId);
// Check if the guardian has enough unlocked tokens to collect the requested amount
// Note that we're also considering the deactivation request if there is any
uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount);
if (_amount > totalUnlockedActiveBalance) {
return false;
}
// Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of
// the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect
// of a guardian deliberately voting in a final round, while drafts occur randomly.
if (_amount > unlockedActiveBalance) {
// No need for SafeMath: amounts were already checked above
uint256 amountToReduce = _amount - unlockedActiveBalance;
_reduceDeactivationRequest(_guardian, amountToReduce, _termId);
}
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianTokensCollected(_guardian, _amount, nextTermId);
return true;
}
/**
* @notice Lock `_guardian`'s withdrawals until term #`_termId`
* @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager {
Guardian storage guardian = guardiansByAddress[_guardian];
guardian.withdrawalsLockTermId = _termId;
}
/**
* @notice Set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor {
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
}
/**
* @dev Tell the total supply of guardian tokens staked
* @return Supply of guardian tokens staked
*/
function totalSupply() external view returns (uint256) {
return guardiansToken.balanceOf(address(this));
}
/**
* @dev Tell the total amount of active guardian tokens
* @return Total amount of active guardian tokens
*/
function totalActiveBalance() external view returns (uint256) {
return tree.getTotal();
}
/**
* @dev Tell the total amount of active guardian tokens for a given term id
* @param _termId Term ID to query on
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) {
return _totalActiveBalanceAt(_termId);
}
/**
* @dev Tell the total balance of tokens held by a guardian
* This includes the active balance, the available balances, and the pending balance for deactivation.
* Note that we don't have to include the locked balances since these represent the amount of active tokens
* that are locked for drafts, i.e. these are already included in the active balance of the guardian.
* @param _guardian Address of the guardian querying the balance of
* @return Total amount of tokens of a guardian
*/
function balanceOf(address _guardian) external view returns (uint256) {
return _balanceOf(_guardian);
}
/**
* @dev Tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the detailed balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function detailedBalanceOf(address _guardian) external view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
return _detailedBalanceOf(_guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID to query on
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) {
return _activeBalanceOfAt(_guardian, _termId);
}
/**
* @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes
* @param _guardian Address of the guardian querying the unlocked balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _currentUnlockedActiveBalanceOf(guardian);
}
/**
* @dev Tell the pending deactivation details for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return amount Amount to be deactivated
* @return availableTermId Term in which the deactivated amount will be available
*/
function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) {
DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest;
return (request.amount, request.availableTermId);
}
/**
* @dev Tell the activation amount locked for a guardian by a lock manager
* @param _guardian Address of the guardian whose info is requested
* @param _lockManager Address of the lock manager querying the lock of
* @return amount Activation amount locked by the lock manager
* @return total Total activation amount locked for the guardian
*/
function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
total = activationLocks.total;
amount = activationLocks.lockedBy[_lockManager];
}
/**
* @dev Tell the withdrawals lock term ID for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return Term ID until which the guardian's withdrawals will be locked
*/
function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) {
return guardiansByAddress[_guardian].withdrawalsLockTermId;
}
/**
* @dev Tell the identification number associated to a guardian address
* @param _guardian Address of the guardian querying the identification number of
* @return Identification number associated to a guardian address, zero in case it wasn't registered yet
*/
function getGuardianId(address _guardian) external view returns (uint256) {
return guardiansByAddress[_guardian].id;
}
/**
* @dev Internal function to activate a given amount of tokens for a guardian.
* This function assumes that the given term is the current term and has already been ensured.
* @param _guardian Address of the guardian to activate tokens
* @param _amount Amount of guardian tokens to be activated
*/
function _activate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if any
_processDeactivationRequest(_guardian, termId);
uint256 availableBalance = guardiansByAddress[_guardian].availableBalance;
uint256 amountToActivate = _amount == 0 ? availableBalance : _amount;
require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT);
uint64 nextTermId = termId + 1;
_checkTotalActiveBalance(nextTermId, amountToActivate);
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 minActiveBalance = _getMinActiveBalance(nextTermId);
if (_existsGuardian(guardian)) {
// Even though we are adding amounts, let's check the new active balance is greater than or equal to the
// minimum active amount. Note that the guardian might have been slashed.
uint256 activeBalance = tree.getItem(guardian.id);
require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
tree.update(guardian.id, nextTermId, amountToActivate, true);
} else {
require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
guardian.id = tree.insert(nextTermId, amountToActivate);
guardiansAddressById[guardian.id] = _guardian;
}
_updateAvailableBalanceOf(_guardian, amountToActivate, false);
emit GuardianActivated(_guardian, nextTermId, amountToActivate);
}
/**
* @dev Internal function to deactivate a given amount of tokens for a guardian.
* @param _guardian Address of the guardian to deactivate tokens
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function _deactivate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount;
require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
// Check future balance is not below the total activation lock of the guardian
// No need for SafeMath: we already checked values above
uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate;
uint256 totalActivationLock = guardian.activationLocks.total;
require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK);
// Check that the guardian is leaving or that the minimum active balance is met
uint256 minActiveBalance = _getMinActiveBalance(termId);
require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
_createDeactivationRequest(_guardian, amountToDeactivate);
}
/**
* @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed
* to process a deactivation request from the next term.
* @param _guardian Address of the guardian to create a token deactivation request for
* @param _amount Amount of guardian tokens requested for deactivation
*/
function _createDeactivationRequest(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if possible
_processDeactivationRequest(_guardian, termId);
uint64 nextTermId = termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
request.amount = request.amount.add(_amount);
request.availableTermId = nextTermId;
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianDeactivationRequested(_guardian, nextTermId, _amount);
}
/**
* @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount
* to the available balance of the guardian if the term when the deactivation was requested has already finished.
* @param _guardian Address of the guardian to process the deactivation request of
* @param _termId Current term id
*/
function _processDeactivationRequest(address _guardian, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint64 deactivationAvailableTermId = request.availableTermId;
// If there is a deactivation request, ensure that the deactivation term has been reached
if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) {
return;
}
uint256 deactivationAmount = request.amount;
// Note that we can use a zeroed term ID to denote void here since we are storing
// the minimum allowed term to deactivate tokens which will always be at least 1.
request.availableTermId = uint64(0);
request.amount = 0;
_updateAvailableBalanceOf(_guardian, deactivationAmount, true);
emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId);
}
/**
* @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request
* cannot be processed for the given term yet.
* @param _guardian Address of the guardian to reduce the deactivation request of
* @param _amount Amount to be reduced from the current deactivation request
* @param _termId Term ID in which the deactivation request is being reduced
*/
function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint256 currentRequestAmount = request.amount;
require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST);
// No need for SafeMath: we already checked values above
uint256 newRequestAmount = currentRequestAmount - _amount;
request.amount = newRequestAmount;
// Move amount back to the tree
tree.update(guardian.id, _termId + 1, _amount, true);
emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId);
}
/**
* @dev Internal function to update the activation locked amount of a guardian
* @param _guardian Guardian to update the activation locked amount of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of tokens to be added to the activation locked amount of the guardian
*/
function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 newTotalLocked = activationLocks.total.add(_amount);
uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
}
/**
* @dev Internal function to stake an amount of tokens for a guardian
* @param _guardian Address of the guardian to deposit the tokens to
* @param _amount Amount of tokens to be deposited
*/
function _stake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
_updateAvailableBalanceOf(_guardian, _amount, true);
emit Staked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to unstake an amount of tokens of a guardian
* @param _guardian Address of the guardian to to unstake the tokens of
* @param _amount Amount of tokens to be unstaked
*/
function _unstake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
// Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure
// the current term this time since deactivation requests always work with future terms, which means that if
// the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here
// to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks.
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
// Check that guardian's withdrawals are not locked
uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId;
require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK);
_processDeactivationRequest(_guardian, lastEnsuredTermId);
_updateAvailableBalanceOf(_guardian, _amount, false);
emit Unstaked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to update the available balance of a guardian
* @param _guardian Guardian to update the available balance of
* @param _amount Amount of tokens to be added to or removed from the available balance of a guardian
* @param _positive True if the given amount should be added, or false to remove it from the available balance
*/
function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal {
// We are not using a require here to avoid reverting in case any of the treasury maths reaches this point
// with a zeroed amount value. Instead, we are doing this validation in the external entry points such as
// stake, unstake, activate, deactivate, among others.
if (_amount == 0) {
return;
}
Guardian storage guardian = guardiansByAddress[_guardian];
if (_positive) {
guardian.availableBalance = guardian.availableBalance.add(_amount);
} else {
require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE);
// No need for SafeMath: we already checked values right above
guardian.availableBalance -= _amount;
}
}
/**
* @dev Internal function to set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal {
require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT);
emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit);
totalActiveBalanceLimit = _totalActiveBalanceLimit;
}
/**
* @dev Internal function to tell the total balance of tokens held by a guardian
* @param _guardian Address of the guardian querying the total balance of
* @return Total amount of tokens of a guardian
*/
function _balanceOf(address _guardian) internal view returns (uint256) {
(uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian);
return available.add(active).add(pendingDeactivation);
}
/**
* @dev Internal function to tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _detailedBalanceOf(address _guardian) internal view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
Guardian storage guardian = guardiansByAddress[_guardian];
active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0;
(available, locked, pendingDeactivation) = _getBalances(guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0;
}
/**
* @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes
* It will use the last value, that might be in a future term
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to check if a guardian was already registered
* @param _guardian Guardian to be checked
* @return True if the given guardian was already registered, false otherwise
*/
function _existsGuardian(Guardian storage _guardian) internal view returns (bool) {
return _guardian.id != 0;
}
/**
* @dev Internal function to get the amount of a deactivation request for a given term id
* @param _guardian Guardian to query the deactivation request amount of
* @param _termId Term ID of the deactivation request to be queried
* @return Amount of the deactivation request for the given term, 0 otherwise
*/
function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) {
DeactivationRequest storage request = _guardian.deactivationRequest;
return request.availableTermId == _termId ? request.amount : 0;
}
/**
* @dev Internal function to tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) {
// This function will return always the same values, the only difference remains on gas costs. In case we look for a
// recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint.
// Otherwise, a binary search is computed.
bool recent = _termId >= _getLastEnsuredTermId();
return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId);
}
/**
* @dev Internal function to check if its possible to add a given new amount to the registry or not
* @param _termId Term ID when the new amount will be added
* @param _amount Amount of tokens willing to be added to the registry
*/
function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view {
uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId);
uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount);
require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED);
}
/**
* @dev Tell the local balance information of a guardian (that is not on the tree)
* @param _guardian Address of the guardian querying the balance information of
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) {
available = _guardian.availableBalance;
locked = _guardian.lockedBalance;
pendingDeactivation = _guardian.deactivationRequest.amount;
}
/**
* @dev Internal function to search guardians in the tree based on certain search restrictions
* @param _params Draft params to be used for the guardians search
* @return ids List of guardian ids obtained based on the requested search
* @return activeBalances List of active balances for each guardian obtained based on the requested search
*/
function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) {
(ids, activeBalances) = tree.batchedRandomSearch(
_params.termRandomness,
_params.disputeId,
_params.termId,
_params.selectedGuardians,
_params.batchRequestedGuardians,
_params.roundRequestedGuardians,
_params.iteration
);
}
/**
* @dev Private function to parse a certain set given of draft params
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return Draft params object parsed
*/
function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) {
uint64 termId = uint64(_params[2]);
uint256 minActiveBalance = _getMinActiveBalance(termId);
return DraftParams({
termRandomness: bytes32(_params[0]),
disputeId: _params[1],
termId: termId,
selectedGuardians: _params[3],
batchRequestedGuardians: _params[4],
roundRequestedGuardians: _params[5],
draftLockAmount: minActiveBalance.pct(uint16(_params[6])),
iteration: 0
});
}
}
|
Internal function to fetch the address of the Config module from the controller return Address of the Config module/ Internal function to get the Court config for a certain term _termId Identification number of the term querying the Court config of return Court config for the given term/
|
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
| 91,764
|
./full_match/80001/0x67eB7ceaec18aFb499D88Db565B92E21ee50d2C0/sources/contracts/Contract.sol
|
We'll use the NFT's `tokenId` as an identifier for the NFT, in the delayed reveal process. Store the encrypted true metadata for the NFT. _setEncryptedBaseURI(tokenId, encryptedPostRevealURI); Mint the NFT in its un-revealed state using `mintTo`, made available by `ERC721Base`.
|
function mintDelayedRevealNFT(
address to,
string memory beforeRevealURI,
bytes memory encryptedPostRevealURI
) public {
uint256 tokenId = nextTokenIdToMint();
_setEncryptedData(tokenId, encryptedPostRevealURI);
mintTo(to, beforeRevealURI);
}
mapping(uint256 => string) private postRevealURI;
| 5,642,378
|
pragma solidity ^0.4.24;
import './RFTFT.sol';
import './RFT.sol';
import './RFTFTMetadata.sol';
import './RFTFTEnumerable.sol';
contract RFTFTFull is RFTFT, RFTFTMetadata, RFTFTEnumerable {
/**
* @dev Constructor for RFTFT full implementation contract
* @param _name - Name for FT
* @param _symbol - Symbol for FT
* @param _decimals - Precision amount for FT
* @param _totalSupply - Max token supply ofr FT
* @param _nftAddress - Address of main NFT contract
* @param _initialTokenId - Unique identifier of dependent NFT
* @param _owner - Address of FT owner
*/
constructor (
string _name,
string _symbol,
uint256 _decimals,
uint256 _totalSupply,
address _nftAddress,
uint256 _initialTokenId,
address _owner
)
public
RFTFTMetadata(
_name,
_symbol,
_decimals
)
RFTFTEnumerable(
_totalSupply,
_nftAddress,
_initialTokenId,
_owner
)
{
}
/**
* @dev Transfer specified token amounts from token holder to receipients
* @notice Means that _receivers[index] address will get _values[index] tokens
* @param _receivers - Array of FT's receivers addresses
* @param _values - Array of FT's amount
*/
function batchTransfer(
address[] _receivers,
uint256[] _values
)
public
returns (bool)
{
require(_receivers.length == _values.length);
for (uint256 i = 0; i < _receivers.length; i++) {
require(transfer(_receivers[i], _values[i]) == true);
}
return true;
}
/**
* @dev Transfer specified token amounts from token holder to receipients
* @notice Allowance balance will be decreased with _values
* @param _from - Holder of NFT's
* @param _receivers - Array of FT's receivers addresses
* @param _values - Array of FT's amount
*/
function batchTransferFrom(
address _from,
address[] _receivers,
uint256[] _values
)
public
returns (bool)
{
require(_receivers.length == _values.length);
for (uint256 i = 0; i < _receivers.length; i++) {
require(transferFrom(_from, _receivers[i], _values[i]) == true);
}
return true;
}
/**
* @dev Overrided transfer function
* @notice Require function caller to be token holder
* @param _to - Address of token receiver
* @param _amount - Token amount to transfer
*/
function transfer(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(tokenHolders[msg.sender] == true);
require(super.transfer(_to, _amount) == true);
if (tokenHolders[_to] == false) {
tokenHolders[_to] = true;
tokenHoldersRegistry.push(_to);
}
return true;
}
/**
* @dev Overrided transferFrom function, to transferFrom function
* @param _from - Address of token sender
* @param _to - Address of token receiver
* @param _amount - Token amount to transfer
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
returns (bool)
{
require(tokenHolders[_from] == true);
require(super.transferFrom(_from, _to, _amount) == true);
if (tokenHolders[_to] == false) {
tokenHolders[_to] = true;
tokenHoldersRegistry.push(_to);
}
return true;
}
}
|
Transfer specified token amounts from token holder to receipients Means that _receivers[index] address will get _values[index] tokens _receivers - Array of FT's receivers addresses _values - Array of FT's amount/
|
function batchTransfer(
address[] _receivers,
uint256[] _values
)
public
returns (bool)
{
require(_receivers.length == _values.length);
for (uint256 i = 0; i < _receivers.length; i++) {
require(transfer(_receivers[i], _values[i]) == true);
}
return true;
}
| 928,603
|
./partial_match/4/0xccf0657c4F0feE437464BFAbeC32E21a8b024809/sources/Comptroller.sol
|
Validates mint and reverts on rejection. May emit logs. cToken Asset being minted minter The address minting the tokens mintAmount The amount of the underlying asset being minted mintTokens The number of tokens being minted/ Shh - currently unused Shh - we don't ever want this hook to be marked pure
|
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external {
cToken;
minter;
mintAmount;
mintTokens;
if (false) {
maxAssets = maxAssets;
}
}
| 8,554,740
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
/// @title: David Ariew X Tatler China
import "../ERC721ProjectUpgradeable.sol";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// '########:::::'###::::'##::::'##:'####:'########::::::::'###::::'########::'####:'########:'##:::::'##::::'##::::'##::::'########::::'###::::'########:'##:::::::'########:'########::::::'######::'##::::'##:'####:'##::: ##::::'###:::: //
// ##.... ##:::'## ##::: ##:::: ##:. ##:: ##.... ##::::::'## ##::: ##.... ##:. ##:: ##.....:: ##:'##: ##::::. ##::'##:::::... ##..::::'## ##:::... ##..:: ##::::::: ##.....:: ##.... ##::::'##... ##: ##:::: ##:. ##:: ###:: ##:::'## ##::: //
// ##:::: ##::'##:. ##:: ##:::: ##:: ##:: ##:::: ##:::::'##:. ##:: ##:::: ##:: ##:: ##::::::: ##: ##: ##:::::. ##'##::::::::: ##:::::'##:. ##::::: ##:::: ##::::::: ##::::::: ##:::: ##:::: ##:::..:: ##:::: ##:: ##:: ####: ##::'##:. ##:: //
// ##:::: ##:'##:::. ##: ##:::: ##:: ##:: ##:::: ##::::'##:::. ##: ########::: ##:: ######::: ##: ##: ##::::::. ###:::::::::: ##::::'##:::. ##:::: ##:::: ##::::::: ######::: ########::::: ##::::::: #########:: ##:: ## ## ##:'##:::. ##: //
// ##:::: ##: #########:. ##:: ##::: ##:: ##:::: ##:::: #########: ##.. ##:::: ##:: ##...:::: ##: ##: ##:::::: ## ##::::::::: ##:::: #########:::: ##:::: ##::::::: ##...:::: ##.. ##:::::: ##::::::: ##.... ##:: ##:: ##. ####: #########: //
// ##:::: ##: ##.... ##::. ## ##:::: ##:: ##:::: ##:::: ##.... ##: ##::. ##::: ##:: ##::::::: ##: ##: ##::::: ##:. ##:::::::: ##:::: ##.... ##:::: ##:::: ##::::::: ##::::::: ##::. ##::::: ##::: ##: ##:::: ##:: ##:: ##:. ###: ##.... ##: //
// ########:: ##:::: ##:::. ###::::'####: ########::::: ##:::: ##: ##:::. ##:'####: ########:. ###. ###::::: ##:::. ##::::::: ##:::: ##:::: ##:::: ##:::: ########: ########: ##:::. ##::::. ######:: ##:::: ##:'####: ##::. ##: ##:::: ##: //
// ........:::..:::::..:::::...:::::....::........::::::..:::::..::..:::::..::....::........:::...::...::::::..:::::..::::::::..:::::..:::::..:::::..:::::........::........::..:::::..::::::......:::..:::::..::....::..::::..::..:::::..:: //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
contract DavidAriewXTatlerChina is ERC721ProjectUpgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() public initializer {
_initialize("David Ariew X Tatler China", "DavidAriewXTatlerChina");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./access/AdminControlUpgradeable.sol";
import "./core/ERC721ProjectCoreUpgradeable.sol";
/**
* @dev ERC721Project implementation
*/
abstract contract ERC721ProjectUpgradeable is
Initializable,
AdminControlUpgradeable,
ERC721Upgradeable,
ERC721ProjectCoreUpgradeable,
UUPSUpgradeable
{
function _initialize(string memory _name, string memory _symbol) internal initializer {
__AdminControl_init();
__ERC721_init(_name, _symbol);
__ERC721ProjectCore_init();
__UUPSUpgradeable_init();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AdminControlUpgradeable, ERC721Upgradeable, ERC721ProjectCoreUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
_approveTransfer(from, to, tokenId);
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(address manager, string calldata baseURI)
external
override
adminRequired
nonBlacklistRequired(manager)
{
_registerManager(manager, baseURI, false);
}
/**
* @dev See {IProjectCore-registerManager}.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external override adminRequired nonBlacklistRequired(manager) {
_registerManager(manager, baseURI, baseURIIdentical);
}
/**
* @dev See {IProjectCore-unregisterManager}.
*/
function unregisterManager(address manager) external override adminRequired {
_unregisterManager(manager);
}
/**
* @dev See {IProjectCore-blacklistManager}.
*/
function blacklistManager(address manager) external override adminRequired {
_blacklistManager(manager);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri) external override managerRequired {
_managerSetBaseTokenURI(uri, false);
}
/**
* @dev See {IProjectCore-managerSetBaseTokenURI}.
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external override managerRequired {
_managerSetBaseTokenURI(uri, identical);
}
/**
* @dev See {IProjectCore-managerSetTokenURIPrefix}.
*/
function managerSetTokenURIPrefix(string calldata prefix) external override managerRequired {
_managerSetTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external override managerRequired {
_managerSetTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-managerSetTokenURI}.
*/
function managerSetTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override managerRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_managerSetTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setBaseTokenURI}.
*/
function setBaseTokenURI(string calldata uri) external override adminRequired {
_setBaseTokenURI(uri);
}
/**
* @dev See {IProjectCore-setTokenURIPrefix}.
*/
function setTokenURIPrefix(string calldata prefix) external override adminRequired {
_setTokenURIPrefix(prefix);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external override adminRequired {
_setTokenURI(tokenId, uri);
}
/**
* @dev See {IProjectCore-setTokenURI}.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "Invalid input");
for (uint256 i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
/**
* @dev See {IProjectCore-setMintPermissions}.
*/
function setMintPermissions(address manager, address permissions) external override adminRequired {
_setMintPermissions(manager, permissions);
}
/**
* @dev See {IERC721ProjectCore-adminMint}.
*/
function adminMint(address to, string calldata uri)
external
virtual
override
nonReentrant
adminRequired
returns (uint256)
{
return _adminMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _adminMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-adminMintBatch}.
*/
function adminMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
adminRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _adminMint(to, uris[i]);
}
return tokenIds;
}
/**
* @dev Mint token with no manager
*/
function _adminMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the manager that minted the token
_tokensManager[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-managerMint}.
*/
function managerMint(address to, string calldata uri)
external
virtual
override
nonReentrant
managerRequired
returns (uint256)
{
return _managerMint(to, uri);
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _managerMint(to, "");
}
return tokenIds;
}
/**
* @dev See {IERC721ProjectCore-managerMintBatch}.
*/
function managerMintBatch(address to, string[] calldata uris)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](uris.length);
for (uint256 i = 0; i < uris.length; i++) {
tokenIds[i] = _managerMint(to, uris[i]);
}
}
/**
* @dev Mint token via manager
*/
function _managerMint(address to, string memory uri) internal virtual returns (uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
_checkMintPermissions(to, tokenId);
// Track the manager that minted the token
_tokensManager[tokenId] = msg.sender;
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintManager(to, tokenId);
return tokenId;
}
/**
* @dev See {IERC721ProjectCore-tokenManager}.
*/
function tokenManager(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "Nonexistent token");
return _tokenManager(tokenId);
}
/**
* @dev See {IERC721ProjectCore-burn}.
*/
function burn(uint256 tokenId) public virtual override nonReentrant {
require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved");
address owner = ownerOf(tokenId);
_burn(tokenId);
_postBurn(owner, tokenId);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints)
external
override
adminRequired
{
_setRoyaltiesManager(address(this), receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyalties}.
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
require(_exists(tokenId), "Nonexistent token");
_setRoyalties(tokenId, receivers, basisPoints);
}
/**
* @dev See {IProjectCore-setRoyaltiesManager}.
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external override adminRequired {
_setRoyaltiesManager(manager, receivers, basisPoints);
}
/**
* @dev {See IProjectCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFees}.
*/
function getFees(uint256 tokenId)
external
view
virtual
override
returns (address payable[] memory, uint256[] memory)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev {See IProjectCore-getFeeRecipients}.
*/
function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyReceivers(tokenId);
}
/**
* @dev {See IProjectCore-getFeeBps}.
*/
function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyBPS(tokenId);
}
/**
* @dev {See IProjectCore-royaltyInfo}.
*/
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata
)
external
view
virtual
override
returns (
address,
uint256,
bytes memory
)
{
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
return _tokenURI(tokenId);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./IAdminControlUpgradeable.sol";
abstract contract AdminControlUpgradeable is
Initializable,
OwnableUpgradeable,
IAdminControlUpgradeable,
ERC165Upgradeable
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// Track registered admins
EnumerableSetUpgradeable.AddressSet private _admins;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __AdminControl_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__ERC165_init_unchained();
__AdminControl_init_unchained();
}
function __AdminControl_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IAdminControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Only allows approved admins to call the specified function
*/
modifier adminRequired() {
require(isAdmin(_msgSender()), "AdminControl: Must be owner or admin");
_;
}
/**
* @dev See {IAdminControl-getAdmins}.
*/
function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint256 i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
return admins;
}
/**
* @dev See {IAdminControl-approveAdmin}.
*/
function approveAdmin(address admin) external override onlyOwner {
if (_admins.add(admin)) {
emit AdminApproved(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-revokeAdmin}.
*/
function revokeAdmin(address admin) external override onlyOwner {
if (_admins.remove(admin)) {
emit AdminRevoked(admin, msg.sender);
}
}
/**
* @dev See {IAdminControl-isAdmin}.
*/
function isAdmin(address admin) public view override returns (bool) {
return (owner() == admin || _admins.contains(admin));
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ERC721/IERC721ProjectApproveTransferManager.sol";
import "../managers/ERC721/IERC721ProjectBurnableManager.sol";
import "../permissions/ERC721/IERC721ProjectMintPermissions.sol";
import "./IERC721ProjectCoreUpgradeable.sol";
import "./ProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project implementation
*/
abstract contract ERC721ProjectCoreUpgradeable is Initializable, ProjectCoreUpgradeable, IERC721ProjectCoreUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev initializer
*/
function __ERC721ProjectCore_init() internal initializer {
__ProjectCore_init_unchained();
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ERC721ProjectCore_init_unchained();
}
function __ERC721ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ProjectCoreUpgradeable, IERC165Upgradeable)
returns (bool)
{
return interfaceId == type(IERC721ProjectCoreUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IProjectCore-managerSetApproveTransfer}.
*/
function managerSetApproveTransfer(bool enabled) external override managerRequired {
require(
!enabled ||
ERC165CheckerUpgradeable.supportsInterface(
msg.sender,
type(IERC721ProjectApproveTransferManager).interfaceId
),
"Manager must implement IERC721ProjectApproveTransferManager"
);
if (_managerApproveTransfers[msg.sender] != enabled) {
_managerApproveTransfers[msg.sender] = enabled;
emit ManagerApproveTransferUpdated(msg.sender, enabled);
}
}
/**
* @dev Set mint permissions for an manager
*/
function _setMintPermissions(address manager, address permissions) internal {
require(_managers.contains(manager), "ProjectCore: Invalid manager");
require(
permissions == address(0x0) ||
ERC165CheckerUpgradeable.supportsInterface(
permissions,
type(IERC721ProjectMintPermissions).interfaceId
),
"Invalid address"
);
if (_managerPermissions[manager] != permissions) {
_managerPermissions[manager] = permissions;
emit MintPermissionsUpdated(manager, permissions, msg.sender);
}
}
/**
* Check if an manager can mint
*/
function _checkMintPermissions(address to, uint256 tokenId) internal {
if (_managerPermissions[msg.sender] != address(0x0)) {
IERC721ProjectMintPermissions(_managerPermissions[msg.sender]).approveMint(msg.sender, to, tokenId);
}
}
/**
* Override for post mint actions
*/
function _postMintBase(address, uint256) internal virtual {}
/**
* Override for post mint actions
*/
function _postMintManager(address, uint256) internal virtual {}
/**
* Post-burning callback and metadata cleanup
*/
function _postBurn(address owner, uint256 tokenId) internal virtual {
// Callback to originating manager if needed
if (_tokensManager[tokenId] != address(this)) {
if (
ERC165CheckerUpgradeable.supportsInterface(
_tokensManager[tokenId],
type(IERC721ProjectBurnableManager).interfaceId
)
) {
IERC721ProjectBurnableManager(_tokensManager[tokenId]).onBurn(owner, tokenId);
}
}
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Delete token origin manager tracking
delete _tokensManager[tokenId];
}
/**
* Approve a transfer
*/
function _approveTransfer(
address from,
address to,
uint256 tokenId
) internal {
if (_managerApproveTransfers[_tokensManager[tokenId]]) {
require(
IERC721ProjectApproveTransferManager(_tokensManager[tokenId]).approveTransfer(from, to, tokenId),
"ERC721Project: Manager approval failure"
);
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
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);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Interface for admin control
*/
interface IAdminControlUpgradeable is IERC165Upgradeable {
event AdminApproved(address indexed account, address indexed sender);
event AdminRevoked(address indexed account, address indexed sender);
/**
* @dev gets address of all admins
*/
function getAdmins() external view returns (address[] memory);
/**
* @dev add an admin. Can only be called by contract owner.
*/
function approveAdmin(address admin) external;
/**
* @dev remove an admin. Can only be called by contract owner.
*/
function revokeAdmin(address admin) external;
/**
* @dev checks whether or not given address is an admin
* Returns True if they are
*/
function isAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your manager to approve a transfer
*/
interface IERC721ProjectApproveTransferManager is IERC165 {
/**
* @dev Set whether or not the project will check the manager for approval of token transfer
*/
function setApproveTransfer(address project, bool enabled) external;
/**
* @dev Called by project contract to approve a transfer
*/
function approveTransfer(
address from,
address to,
uint256 tokenId
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Your manager is required to implement this interface if it wishes
* to receive the onBurn callback whenever a token the manager created is
* burned
*/
interface IERC721ProjectBurnableManager is IERC165 {
/**
* @dev callback handler for burn events
*/
function onBurn(address owner, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721Project compliant manager contracts.
*/
interface IERC721ProjectMintPermissions is IERC165 {
/**
* @dev get approval to mint
*/
function approveMint(
address manager,
address to,
uint256 tokenId
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core ERC721 project interface
*/
interface IERC721ProjectCoreUpgradeable is IProjectCoreUpgradeable {
/**
* @dev mint a token with no manager. Can only be called by an admin. set uri to empty string to use default uri.
* Returns tokenId minted
*/
function adminMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no manager. Can only be called by an admin.
* Returns tokenId minted
*/
function adminMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered manager. set uri to "" to use default uri
* Returns tokenId minted
*/
function managerMint(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenIds minted
*/
function managerMintBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered manager.
* Returns tokenId minted
*/
function managerMintBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered manager's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../managers/ProjectTokenURIManager/IProjectTokenURIManager.sol";
import "./IProjectCoreUpgradeable.sol";
/**
* @dev Core project implementation
*/
abstract contract ProjectCoreUpgradeable is
Initializable,
IProjectCoreUpgradeable,
ReentrancyGuardUpgradeable,
ERC165Upgradeable
{
using StringsUpgradeable for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
/**
* External interface identifiers for royalties
*/
/**
* @dev ProjectCore
*
* bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6
*
* => 0xbb3bafd6 = 0xbb3bafd6
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_PROJECTCORE = 0xbb3bafd6;
/**
* @dev Rarible: RoyaltiesV1
*
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
*
* => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584;
/**
* @dev Foundation
*
* bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c
*
* => 0xd5a06d4c = 0xd5a06d4c
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c;
/**
* @dev EIP-2981
*
* bytes4(keccak256("royaltyInfo(uint256,uint256,bytes)")) == 0x6057361d
*
* => 0x6057361d = 0x6057361d
*/
bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x6057361d;
uint256 _tokenCount;
// Track registered managers data
EnumerableSetUpgradeable.AddressSet internal _managers;
EnumerableSetUpgradeable.AddressSet internal _blacklistedManagers;
mapping(address => address) internal _managerPermissions;
mapping(address => bool) internal _managerApproveTransfers;
// For tracking which manager a token was minted by
mapping(uint256 => address) internal _tokensManager;
// The baseURI for a given manager
mapping(address => string) private _managerBaseURI;
mapping(address => bool) private _managerBaseURIIdentical;
// The prefix for any tokens with a uri configured
mapping(address => string) private _managerURIPrefix;
// Mapping for individual token URIs
mapping(uint256 => string) internal _tokenURIs;
// Royalty configurations
mapping(address => address payable[]) internal _managerRoyaltyReceivers;
mapping(address => uint256[]) internal _managerRoyaltyBPS;
mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers;
mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS;
/**
* @dev initializer
*/
function __ProjectCore_init() internal initializer {
__ReentrancyGuard_init_unchained();
__ERC165_init_unchained();
__ProjectCore_init_unchained();
_tokenCount = 0;
}
function __ProjectCore_init_unchained() internal initializer {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IProjectCoreUpgradeable).interfaceId ||
super.supportsInterface(interfaceId) ||
interfaceId == _INTERFACE_ID_ROYALTIES_PROJECTCORE ||
interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE ||
interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION ||
interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
/**
* @dev Only allows registered managers to call the specified function
*/
modifier managerRequired() {
require(_managers.contains(msg.sender), "Must be registered manager");
_;
}
/**
* @dev Only allows non-blacklisted managers
*/
modifier nonBlacklistRequired(address manager) {
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
_;
}
/**
* @dev totalSupply
*/
function totalSupply() public view override returns (uint256) {
return _tokenCount;
}
/**
* @dev See {IProjectCore-getManagers}.
*/
function getManagers() external view override returns (address[] memory managers) {
managers = new address[](_managers.length());
for (uint256 i = 0; i < _managers.length(); i++) {
managers[i] = _managers.at(i);
}
return managers;
}
/**
* @dev Register an manager
*/
function _registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) internal {
require(manager != address(this), "Project: Invalid");
require(manager.isContract(), "Project: Manager must be a contract");
if (_managers.add(manager)) {
_managerBaseURI[manager] = baseURI;
_managerBaseURIIdentical[manager] = baseURIIdentical;
emit ManagerRegistered(manager, msg.sender);
}
}
/**
* @dev Unregister an manager
*/
function _unregisterManager(address manager) internal {
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
}
/**
* @dev Blacklist an manager
*/
function _blacklistManager(address manager) internal {
require(manager != address(this), "Cannot blacklist yourself");
if (_managers.remove(manager)) {
emit ManagerUnregistered(manager, msg.sender);
}
if (_blacklistedManagers.add(manager)) {
emit ManagerBlacklisted(manager, msg.sender);
}
}
/**
* @dev Set base token uri for an manager
*/
function _managerSetBaseTokenURI(string calldata uri, bool identical) internal {
_managerBaseURI[msg.sender] = uri;
_managerBaseURIIdentical[msg.sender] = identical;
}
/**
* @dev Set token uri prefix for an manager
*/
function _managerSetTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[msg.sender] = prefix;
}
/**
* @dev Set token uri for a token of an manager
*/
function _managerSetTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == msg.sender, "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Set base token uri for tokens with no manager
*/
function _setBaseTokenURI(string memory uri) internal {
_managerBaseURI[address(this)] = uri;
}
/**
* @dev Set token uri prefix for tokens with no manager
*/
function _setTokenURIPrefix(string calldata prefix) internal {
_managerURIPrefix[address(this)] = prefix;
}
/**
* @dev Set token uri for a token with no manager
*/
function _setTokenURI(uint256 tokenId, string calldata uri) internal {
require(_tokensManager[tokenId] == address(this), "Invalid token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Retrieve a token's URI
*/
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
address manager = _tokensManager[tokenId];
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
// 1. if tokenURI is stored in this contract, use it with managerURIPrefix if any
if (bytes(_tokenURIs[tokenId]).length != 0) {
if (bytes(_managerURIPrefix[manager]).length != 0) {
return string(abi.encodePacked(_managerURIPrefix[manager], _tokenURIs[tokenId]));
}
return _tokenURIs[tokenId];
}
// 2. if URI is controlled by manager, retrieve it from manager
if (ERC165CheckerUpgradeable.supportsInterface(manager, type(IProjectTokenURIManager).interfaceId)) {
return IProjectTokenURIManager(manager).tokenURI(address(this), tokenId);
}
// 3. use managerBaseURI with id or not
if (!_managerBaseURIIdentical[manager]) {
return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString()));
} else {
return _managerBaseURI[manager];
}
}
/**
* Get token manager
*/
function _tokenManager(uint256 tokenId) internal view returns (address manager) {
manager = _tokensManager[tokenId];
require(manager != address(this), "No manager for token");
require(!_blacklistedManagers.contains(manager), "Manager blacklisted");
return manager;
}
/**
* Helper to get royalties for a token
*/
function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) {
return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId));
}
/**
* Helper to get royalty receivers for a token
*/
function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) {
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_managerRoyaltyReceivers[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyReceivers[_tokensManager[tokenId]];
}
return _managerRoyaltyReceivers[address(this)];
}
/**
* Helper to get royalty basis points for a token
*/
function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) {
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_managerRoyaltyBPS[_tokensManager[tokenId]].length > 0) {
return _managerRoyaltyBPS[_tokensManager[tokenId]];
}
return _managerRoyaltyBPS[address(this)];
}
function _getRoyaltyInfo(uint256 tokenId, uint256 value)
internal
view
returns (
address receiver,
uint256 amount,
bytes memory data
)
{
address payable[] storage receivers = _getRoyaltyReceivers(tokenId);
require(receivers.length <= 1, "More than 1 royalty receiver");
if (receivers.length == 0) {
return (address(this), 0, data);
}
return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000, data);
}
/**
* Set royalties for a token
*/
function _setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_tokenRoyaltyReceivers[tokenId] = receivers;
_tokenRoyaltyBPS[tokenId] = basisPoints;
emit RoyaltiesUpdated(tokenId, receivers, basisPoints);
}
/**
* Set royalties for all tokens of an manager
*/
function _setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) internal {
require(receivers.length == basisPoints.length, "Invalid input");
uint256 totalBasisPoints;
for (uint256 i = 0; i < basisPoints.length; i++) {
totalBasisPoints += basisPoints[i];
}
require(totalBasisPoints < 10000, "Invalid total royalties");
_managerRoyaltyReceivers[manager] = receivers;
_managerRoyaltyBPS[manager] = basisPoints;
if (manager == address(this)) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit ManagerRoyaltiesUpdated(manager, receivers, basisPoints);
}
}
uint256[36] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Core project interface
*/
interface IProjectCoreUpgradeable is IERC165Upgradeable {
event ManagerRegistered(address indexed manager, address indexed sender);
event ManagerUnregistered(address indexed manager, address indexed sender);
event ManagerBlacklisted(address indexed manager, address indexed sender);
event MintPermissionsUpdated(address indexed manager, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ManagerRoyaltiesUpdated(address indexed manager, address payable[] receivers, uint256[] basisPoints);
event ManagerApproveTransferUpdated(address indexed manager, bool enabled);
/**
* @dev totalSupply
*/
function totalSupply() external view returns (uint256);
/**
* @dev gets address of all managers
*/
function getManagers() external view returns (address[] memory);
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(address manager, string calldata baseURI) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* manager address must point to a contract implementing IProjectManager.
* Returns True if newly added, False if already added.
*/
function registerManager(
address manager,
string calldata baseURI,
bool baseURIIdentical
) external;
/**
* @dev add an manager. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterManager(address manager) external;
/**
* @dev blacklist an manager. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified manager. It will also unregister the manager if needed.
* Returns True if removed, False if already removed.
*/
function blacklistManager(address manager) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
*/
function managerSetBaseTokenURI(string calldata uri) external;
/**
* @dev set the baseTokenURI of an manager. Can only be called by manager.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function managerSetBaseTokenURI(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an manager. Can only be called by manager.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function managerSetTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token manager. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token manager for multiple tokens. Can only be called by manager that minted token.
*/
function managerSetTokenURI(uint256[] calldata tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no manager. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no manager. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no manager. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] calldata tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an manager. Used to control minting.
*/
function setMintPermissions(address manager, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be manager) gets approval
* from the manager before transferring
*/
function managerSetApproveTransfer(bool enabled) external;
/**
* @dev get the manager of a given token
*/
function tokenManager(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(
uint256 tokenId,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Set royalties of an manager
*/
function setRoyaltiesManager(
address manager,
address payable[] calldata receivers,
uint256[] calldata basisPoints
) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint256[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(
uint256 tokenId,
uint256 value,
bytes calldata data
)
external
view
returns (
address,
uint256,
bytes memory
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165CheckerUpgradeable {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable(account).supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your manager to have overloadable URI's
*/
interface IProjectTokenURIManager is IERC165 {
/**
* Get the uri for a given project/tokenId
*/
function tokenURI(address project, uint256 tokenId) external view returns (string memory);
}
|
See {IERC721ProjectCore-managerMintBatch}./
|
function managerMintBatch(address to, uint16 count)
external
virtual
override
nonReentrant
managerRequired
returns (uint256[] memory tokenIds)
{
tokenIds = new uint256[](count);
for (uint16 i = 0; i < count; i++) {
tokenIds[i] = _managerMint(to, "");
}
return tokenIds;
}
| 12,006,228
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IMintableERC20 } from "../MintableERC20.sol";
import { ICurvePool } from "../../strategies/ICurvePool.sol";
import { StableMath } from "../../utils/StableMath.sol";
import "../../utils/Helpers.sol";
contract MockCurvePool {
using StableMath for uint256;
address[] public coins;
uint256[2] public balances;
address lpToken;
constructor(address[2] memory _coins, address _lpToken) {
coins = _coins;
lpToken = _lpToken;
}
// Returns the same amount of LP tokens in 1e18 decimals
function add_liquidity(uint256[2] calldata _amounts, uint256 _minAmount)
external
{
uint256 sum = 0;
for (uint256 i = 0; i < _amounts.length; i++) {
if (_amounts[i] > 0) {
IERC20(coins[i]).transferFrom(
msg.sender,
address(this),
_amounts[i]
);
uint256 assetDecimals = Helpers.getDecimals(coins[i]);
// Convert to 1e18 and add to sum
sum += _amounts[i].scaleBy(18, assetDecimals);
balances[i] = balances[i] + _amounts[i];
}
}
// Hacky way of simulating slippage to check _minAmount
if (sum == 29000e18) sum = 14500e18;
require(sum >= _minAmount, "Slippage ruined your day");
// Send LP token to sender, e.g. 3CRV
IMintableERC20(lpToken).mint(sum);
IERC20(lpToken).transfer(msg.sender, sum);
}
// Dumb implementation that returns the same amount
function calc_withdraw_one_coin(uint256 _amount, int128 _index)
public
view
returns (uint256)
{
uint256 assetDecimals = Helpers.getDecimals(coins[uint128(_index)]);
return _amount.scaleBy(assetDecimals, 18);
}
function remove_liquidity_one_coin(
uint256 _amount,
int128 _index,
uint256 _minAmount
) external {
IERC20(lpToken).transferFrom(msg.sender, address(this), _amount);
uint256[] memory amounts = new uint256[](coins.length);
amounts[uint128(_index)] = _amount;
uint256 amount = calc_withdraw_one_coin(_amount, _index);
IERC20(coins[uint128(_index)]).transfer(msg.sender, amount);
balances[uint128(_index)] = balances[uint128(_index)] - amount;
}
function get_virtual_price() external pure returns (uint256) {
return 1 * 10**18;
}
function remove_liquidity(uint256 _amount, uint256[2] memory _min_amounts)
public
{
IERC20(lpToken).transferFrom(msg.sender, address(this), _amount);
uint256 totalSupply = IERC20(lpToken).totalSupply();
for (uint256 i = 0; i < 2; i++) {
uint256 amount = (_amount / totalSupply) *
IERC20(coins[i]).balanceOf(address(this));
IERC20(coins[i]).transfer(msg.sender, amount);
balances[i] = balances[i] - amount;
}
}
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burned_tokens
) public {
IERC20(lpToken).transferFrom(
msg.sender,
address(this),
_max_burned_tokens
);
for (uint256 i = 0; i < _amounts.length; i++) {
IERC20(coins[i]).transfer(msg.sender, _amounts[i]);
balances[i] = balances[i] - _amounts[i];
}
}
}
|
Dumb implementation that returns the same amount
|
function calc_withdraw_one_coin(uint256 _amount, int128 _index)
public
view
returns (uint256)
{
uint256 assetDecimals = Helpers.getDecimals(coins[uint128(_index)]);
return _amount.scaleBy(assetDecimals, 18);
}
| 12,667,969
|
./partial_match/44787/0xbFD3c8A956AFB7a9754C951D03C9aDdA7EC5d638/sources/src/Interest/InterestModule.sol
|
--- Public Debt Methods --- increases the debt of a loan by a currencyAmount a change of the loan debt updates the rate debt and total debt
|
function incDebt(uint256 loan, uint256 currencyAmount) external auth {
uint256 rate = loanRates[loan];
require(
block.timestamp == rates[rate].lastUpdated,
"rate-group-not-updated"
);
currencyAmount = (currencyAmount +
rmul(currencyAmount, rates[rate].fixedRate));
uint256 pieAmount = toPie(rates[rate].chi, currencyAmount);
pie[loan] = (pie[loan] + pieAmount);
rates[rate].pie = (rates[rate].pie + pieAmount);
emit IncreaseDebt(loan, currencyAmount);
}
| 16,954,460
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import {
ISuperfluid,
ISuperToken,
ISuperAgreement,
SuperAppDefinitions
} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol";
import {
IConstantFlowAgreementV1
} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol";
import {
SuperAppBase
} from "@superfluid-finance/ethereum-contracts/contracts/apps/SuperAppBase.sol";
import {
ISuperAuction
} from "./interfaces/ISuperAuction.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@superfluid-finance/ethereum-contracts/contracts/utils/Int96SafeMath.sol";
contract SuperAuction is Ownable, SuperAppBase, ISuperAuction {
using Int96SafeMath for int96;
using SafeMath for uint256;
using SignedSafeMath for int256;
struct Bidder {
uint256 cumulativeTimer;
uint256 lastSettleAmount;
address nextAccount;
}
uint256 public immutable override streamTime;
address public override winner;
int96 public override winnerFlowRate;
uint256 public override lastTick;
int96 public override immutable step;
bool public override isFinish;
mapping(address => Bidder) public override bidders;
address public immutable nftContract;
uint256 public immutable tokenId;
ISuperfluid private _host;
IConstantFlowAgreementV1 public immutable override _cfa;
ISuperToken public immutable override _superToken;
constructor(
ISuperfluid host,
IConstantFlowAgreementV1 cfa,
ISuperToken superToken,
address nft,
uint256 _tokenId,
uint256 winnerTime,
int96 stepBid,
string memory registrationKey
) {
require(address(host) != address(0), "Auction: host is empty");
require(address(cfa) != address(0), "Auction: cfa is empty");
require(address(superToken) != address(0), "Auction: superToken is empty");
require(nft != address(0), "Auction: NFT contract is empty");
require(winnerTime > 0, "Auction: Provide a winner stream time");
require(stepBid > 0 && stepBid <=100, "Auction: Step value wrong" );
_host = host;
_cfa = cfa;
nftContract = nft;
tokenId = _tokenId;
_superToken = superToken;
streamTime = winnerTime;
step = stepBid + 100;
uint256 configWord =
SuperAppDefinitions.APP_LEVEL_FINAL |
SuperAppDefinitions.BEFORE_AGREEMENT_CREATED_NOOP |
SuperAppDefinitions.BEFORE_AGREEMENT_UPDATED_NOOP |
SuperAppDefinitions.BEFORE_AGREEMENT_TERMINATED_NOOP;
if(bytes(registrationKey).length > 0) {
_host.registerAppWithKey(configWord, registrationKey);
} else {
_host.registerApp(configWord);
}
}
/**
* @dev Set Auction to finish state. Has to exist one winner
*/
function finishAuction() public {
_endAuction();
}
/**
* @dev Set Auction to finish state. Check winner time of flow to close auction
*/
function _endAuction() private {
if(!isFinish && winner != address(0)) {
if(bidders[winner].cumulativeTimer.add(
block.timestamp.sub(lastTick)
) >= streamTime) {
isFinish = true;
emit Winner(winner);
emit AuctionClosed();
}
}
}
/**************************************************************************
* CFA Reative Functions
*************************************************************************/
/**
* @dev Add new player to Auction.
* @param account Address joining the auction.
* @param flowRate Flow rate in amount per second for this flow.
* @param ctx Context from Superfluid callback.
* @return newCtx NewCtx to Superfluid callback caller.
*/
function _newPlayer(
address account,
int96 flowRate,
bytes memory ctx
)
private
isRunning
returns(bytes memory newCtx)
{
require(
(flowRate.mul(100, "Int96SafeMath : multiplication error")) >=
(winnerFlowRate.mul(step, "Int96SafeMath: multiplication error")),
"Auction: FlowRate is not enough"
);
require(bidders[account].cumulativeTimer == 0, "Auction: sorry no rejoins");
newCtx = ctx;
_endAuction();
if(!isFinish) {
bidders[account].nextAccount = winner;
if(winner != address(0)) {
_settleWinnerAccount();
newCtx = _startStream(winner, winnerFlowRate, ctx);
} else {
lastTick = block.timestamp;
}
winner = account;
winnerFlowRate = flowRate;
emit NewHighestBid(winner, winnerFlowRate);
} else {
revert("Auction: Closed auction.");
}
}
/**
* @dev Update player flowRate. Each call will try to close the auction.
* @param account Address to update.
* @param ctx Context from Superfluid callback.
* @return newCtx NewCtx to Superfluid callback caller.
*/
function _updatePlayer(
address account,
bytes memory ctx
)
private
isRunning
returns(bytes memory newCtx)
{
newCtx = ctx;
(, int96 flowRate) = _getFlowInfo(account, address(this));
require(
(flowRate.mul(100, "Int96SafeMath: multiplication error"))
>= (winnerFlowRate.mul(step,"Int96SafeMath: multiplication error")
), "Auction: FlowRate is not enough"
);
_endAuction();
if(!isFinish) {
address oldWinner = winner;
_settleWinnerAccount();
if(account != winner) {
address previousAccount = abi.decode(_host.decodeCtx(ctx).userData, (address));
require(bidders[previousAccount].nextAccount == account, "Auction: Previous Bidder is wrong");
bidders[previousAccount].nextAccount = bidders[account].nextAccount;
newCtx = _endStream(address(this), account, newCtx);
newCtx = _startStream(oldWinner, winnerFlowRate, newCtx);
bidders[account].nextAccount = oldWinner;
winner = account;
}
winnerFlowRate = flowRate;
emit NewHighestBid(winner, winnerFlowRate);
} else {
revert("Auction: Closed auction.");
}
}
/**
* @dev Drop player from auction. Each call will try to close the auction.
* @param account Address to drop.
* @param ctx Context from Superfluid callback.
* @return newCtx NewCtx to Superfluid callback caller.
*/
function _dropPlayer(
address account,
bytes memory ctx
)
private
returns(bytes memory newCtx)
{
newCtx = ctx;
_endAuction();
if(!isFinish) {
emit DropPlayer(account);
if(account == winner) {
//if winner there is no reverse back stream, we just settle the current stream
_settleWinnerAccount();
//Find next winner
if(bidders[winner].nextAccount != address(0)) {
address next = bidders[winner].nextAccount;
//Unlink present winner from queque
delete bidders[winner].nextAccount;
int96 flowRate;
while(next != address(0)) {
(, flowRate) = _getFlowInfo(next, address(this));
if(flowRate > 0) {
winnerFlowRate = flowRate;
winner = next;
emit NewHighestBid(winner, flowRate);
//Close reverse back stream to next winner
return _endStream(address(this), next, newCtx);
}
next = bidders[next].nextAccount;
}
}
//Note: There is no winner in list.
delete winner;
delete winnerFlowRate;
delete lastTick;
} else {
newCtx = _endStream(account, address(this), newCtx);
newCtx = _endStream(address(this), account, newCtx);
}
} else {
if(account != winner) {
newCtx = _endStream(account, address(this), newCtx);
newCtx = _endStream(address(this), account, newCtx);
_withdrawNonWinnerPlayer(account);
}
//If there is a winner, settle balance close that stream
if(winnerFlowRate > 0) {
_settleWinnerAccount();
newCtx = _endStream(winner, address(this), newCtx);
delete winnerFlowRate;
}
}
}
/**
* @dev Get the Flow Rate the player is sending to auction contract.
* @param sender Address to query.
* @return timestamp of the stream.
* @return flowRate of the stream.
*/
function _getFlowInfo(
address sender,
address receiver
)
private
view
returns (uint256 timestamp, int96 flowRate)
{
(timestamp, flowRate , ,) = _cfa.getFlow(_superToken, sender, receiver);
}
/**
* @dev Get the Settlement information for player.
* @param account Address to get information.
* @return settleBalance of the player.
* @return cumulativeTimer of the player.
*/
function getSettledInfo(
address account
)
public
view
override
returns(
uint256 settleBalance,
uint256 cumulativeTimer
)
{
if(account == winner) {
cumulativeTimer = ((block.timestamp).sub(lastTick));
settleBalance = cumulativeTimer.mul(uint256(winnerFlowRate));
} else {
cumulativeTimer = bidders[account].cumulativeTimer;
settleBalance = bidders[account].lastSettleAmount;
}
}
/**
* @dev Change Winner settlement information.
* @notice call the settlement before chaging the global winner / winnerFlowRate variables
*/
function _settleWinnerAccount()
private
{
(uint256 settleBalance, uint256 cumulativeTimer) = getSettledInfo(winner);
bidders[winner].cumulativeTimer = bidders[winner].cumulativeTimer.add(cumulativeTimer);
bidders[winner].lastSettleAmount = bidders[winner].lastSettleAmount.add(settleBalance);
lastTick = block.timestamp;
}
/**
* @dev Non winners players collect the settlement tokens balance in the end.
* @param account Address to send SuperTokens.
*/
function _withdrawNonWinnerPlayer(address account) private {
uint256 settleBalance = bidders[account].lastSettleAmount;
bidders[account].lastSettleAmount = 0;
if(_superToken.balanceOf(address(this)) >= settleBalance) {
_superToken.transferFrom(address(this), account, settleBalance);
}
}
/**
* @dev Non winner players retrive balance.
*/
function withdrawNonWinner() external {
require(msg.sender != winner, "Auction: Caller is the winner");
require(isFinish, "Auction: Still running");
(, int96 flowRate) = _getFlowInfo(address(this), msg.sender);
require(flowRate == 0, "Auction: Close your stream to auction");
_withdrawNonWinnerPlayer(msg.sender);
}
/**
* @dev Owner collects winners bid payment.
*/
function withdraw() external onlyOwner {
require(isFinish, "Auction: Still running");
assert(_superToken.transferFrom(
address(this),
owner(),
bidders[winner].lastSettleAmount)
);
}
function withdrawAmount(uint256 amount) external onlyOwner {
assert(_superToken.transferFrom(address(this), owner(), amount));
}
/**
* @dev Owner can stop the auction if there is no winner.
*/
function stopAuction() external onlyOwner isRunning {
if(winner == address(0)) {
isFinish = true;
}
}
/**************************************************************************
* Constant Flow Agreements Functions
*************************************************************************/
/**
* @dev Helper function to start a stream from auction to user.
* @param account Address to drop.
* @param flowRate Flow rate to send.
* @param ctx Context from Superfluid callback.
* @return newCtx NewCtx to Superfluid callback caller.
*/
function _startStream(
address account,
int96 flowRate,
bytes memory ctx
)
private
returns(bytes memory newCtx)
{
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.createFlow.selector,
_superToken,
account,
flowRate,
new bytes(0)
),
"0x",
ctx
);
}
/**
* @dev Helper function to stop a stream from auction to user.
* @param receiver Address to stop sending the stream.
* @param ctx Context from Superfluid callback.
* @return newCtx NewCtx to Superfluid callback caller.
*/
function _endStream(
address sender,
address receiver,
bytes memory ctx
)
private
returns(bytes memory newCtx)
{
newCtx = ctx;
(, int96 flowRate) = _getFlowInfo(sender, receiver);
if(flowRate > int96(0)) {
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
_superToken,
sender,
receiver,
new bytes(0)
),
"0x",
ctx
);
}
}
/**************************************************************************
* SuperApp callbacks
* https://github.com/superfluid-finance/protocol-monorepo/tree/master/packages/ethereum-contracts
*************************************************************************/
function afterAgreementCreated(
ISuperToken superToken,
address agreementClass,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata /*cbdata*/,
bytes calldata ctx
)
external
override
onlyHost
onlyExpected(superToken, agreementClass)
isRunning
returns (bytes memory newCtx)
{
address account = _host.decodeCtx(ctx).msgSender;
(, int96 flowRate) = _getFlowInfo(account, address(this));
return _newPlayer(account, flowRate, ctx);
}
function afterAgreementUpdated(
ISuperToken superToken,
address agreementClass,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata /*cbdata*/,
bytes calldata ctx
)
external
override
onlyHost
onlyExpected(superToken, agreementClass)
returns (bytes memory newCtx)
{
return _updatePlayer(
_host.decodeCtx(ctx).msgSender,
ctx
);
}
function afterAgreementTerminated(
ISuperToken superToken,
address agreementClass,
bytes32 /*agreementId*/,
bytes calldata agreementData,
bytes calldata /*cbdata*/,
bytes calldata ctx
)
external
override
onlyHost
returns (bytes memory newCtx) {
newCtx = ctx;
if(_isSameToken(superToken) && _isCFAv1(agreementClass)) {
(address sender, address receiver) = abi.decode(agreementData, (address, address));
newCtx = _dropPlayer(sender == address(this) ? receiver : sender, ctx);
}
}
function _isSameToken(ISuperToken superToken) private view returns (bool) {
return address(superToken) == address(_superToken);
}
function _isCFAv1(address agreementClass) private view returns (bool) {
return ISuperAgreement(agreementClass).agreementType()
== keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1");
}
/*Modifier*/
modifier isRunning() {
require(!isFinish, "Auction: Not running");
_;
}
modifier onlyHost() {
require(msg.sender == address(_host), "Auction: support only one host");
_;
}
modifier onlyExpected(ISuperToken superToken, address agreementClass) {
require(_isSameToken(superToken), "Auction: not accepted token");
require(_isCFAv1(agreementClass), "Auction: only CFAv1 supported");
_;
}
}
|
Add new player to Auction. account Address joining the auction. flowRate Flow rate in amount per second for this flow. ctx Context from Superfluid callback. return newCtx NewCtx to Superfluid callback caller./
|
function _newPlayer(
address account,
int96 flowRate,
bytes memory ctx
)
private
isRunning
returns(bytes memory newCtx)
{
require(
(flowRate.mul(100, "Int96SafeMath : multiplication error")) >=
(winnerFlowRate.mul(step, "Int96SafeMath: multiplication error")),
"Auction: FlowRate is not enough"
);
require(bidders[account].cumulativeTimer == 0, "Auction: sorry no rejoins");
newCtx = ctx;
_endAuction();
if(!isFinish) {
bidders[account].nextAccount = winner;
if(winner != address(0)) {
_settleWinnerAccount();
newCtx = _startStream(winner, winnerFlowRate, ctx);
lastTick = block.timestamp;
}
winner = account;
winnerFlowRate = flowRate;
emit NewHighestBid(winner, winnerFlowRate);
revert("Auction: Closed auction.");
}
}
| 15,870,932
|
./full_match/80001/0x19c7ce67eF3d8f0F89CE8DB445E6fA2a2934053a/sources/contracts/votacion.sol
|
Cualquier persona puede usar esta funcion para presentarse a las eleccionesHash de los datos del candidatoAlmacenamos el hash de los datos del candidato ligados a su nombreAlmacenamos el nombre del candidato
|
function Representar(
string memory _nombrePersona,
uint256 _edadPersona,
string memory _idPersona
) public {
bytes32 hash_Candidato = keccak256(
abi.encodePacked(_nombrePersona, _edadPersona, _idPersona)
);
ID_Candidato[_nombrePersona] = hash_Candidato;
candidatos.push(_nombrePersona);
cantidadCandi++;
}
| 5,564,516
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IMatter.sol";
import "./@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "./@openzeppelin/contracts/utils/Counters.sol";
import "./@openzeppelin/contracts/access/Ownable.sol";
import "./@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
contract Merge is ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _matterIds;
struct MatterMeta {
uint256 id;
uint256 tokenId;
}
mapping(address => uint256) private _metaMatterIds;
mapping(address => MatterMeta[]) private _tokenOwners;
bool private _isStopTransfer = true;
address private _matterNFTContract;
constructor() ERC721("MatterMerge", "MTMG") {}
function burn(uint256 tokenId) internal {
_burn(tokenId);
}
function _beforeMatterTransfer() internal view {
require(!_isStopTransfer, "matter token transfer while paused");
}
function setMatterContract(address matterNFT)
public
onlyOwner
returns (address)
{
_matterNFTContract = matterNFT;
return matterNFT;
}
function matterContract() public view returns (address) {
return _matterNFTContract;
}
// erc721合约地址,需要防止重放攻击
function addMetaMatter(address metaMatter)
public
onlyOwner
returns (uint256)
{
// 需要确保唯一性, 保证每一个原Matter只能被添加一次
require(_metaMatterIds[metaMatter] == 0, "metaMatter already exists");
_matterIds.increment();
uint256 matterId = _matterIds.current();
_mint(metaMatter, matterId);
// 将原matter合约和id关联起来
_metaMatterIds[metaMatter] = matterId;
return matterId;
}
// 销毁已经添加的matter
function burnMetaMatter(uint256 tokenId)
public
onlyOwner
returns (uint256)
{
address metaMatterContract = ownerOf(tokenId);
// 判断元物质是否被添加
require(tokenId != 0, "meta matter not exist");
delete _metaMatterIds[metaMatterContract];
burn(tokenId);
return tokenId;
}
// 获取当前原Matter的id
function getMetaMatterId(address metaMatter) public view returns (uint256) {
return _metaMatterIds[metaMatter];
}
// 保存指定matter的信息
function _saveMatter(uint256 matterId, uint256 tokenId) private {
address sender = _msgSender();
// 如果当前地址没有初始化则进行初始化
// if (_tokenOwners[sender].length == 0) {
// _tokenOwners[sender] = address[0];
// }
// 把当前存入到合约中的nft放入对应的账户中
_tokenOwners[sender].push(MatterMeta(matterId, tokenId));
}
// 保存指定matter的信息
function _saveMatter(
address owner,
uint256 matterId,
uint256 tokenId
) private {
// 如果当前地址没有初始化则进行初始化
// if (_tokenOwners[owner] == 0) {
// _tokenOwners[owner] = address[];
// }
// 把当前存入到合约中的nft放入对应的账户中
_tokenOwners[owner].push(MatterMeta(matterId, tokenId));
}
// 移除指定的matter
function _deleteMatter(
address owner,
uint256 matterId,
uint256 tokenId
) private {
// 如果当前地址没有初始化则进行初始化
// if (_tokenOwners[owner] == 0) {
// _tokenOwners[owner] = address[];
// }
bool isExist = false;
uint256 resultIdx = 0;
for (uint256 i = 0; i < _tokenOwners[owner].length; i++) {
if (
_tokenOwners[owner][i].id == matterId &&
_tokenOwners[owner][i].tokenId == tokenId
) {
resultIdx = i;
isExist = true;
break;
}
}
require(isExist, "matter not exist");
// 把当前存入到合约中的nft放入对应的账户中
// delete _tokenOwners[owner][resultIdx];
// require(resultIdx < _tokenOwners[owner].length);
_tokenOwners[owner][resultIdx] = _tokenOwners[owner][
_tokenOwners[owner].length - 1
];
_tokenOwners[owner].pop();
}
// 获取指定用户可用的matter
function matterOf(address owner) public view returns (MatterMeta[] memory) {
require(owner != address(0), "owner is not valid");
MatterMeta[] memory owners = _tokenOwners[owner];
return owners;
}
// 任何人都可以存入自己的nft到合约中
function deposit(uint256 metaMatterId, uint256 tokenId)
public
returns (uint256)
{
// 获取erc721指定的合约地址
address tokenContract = ownerOf(metaMatterId);
address sender = _msgSender();
IERC721 token = IERC721(tokenContract);
// 将tokenId存入合约中
token.safeTransferFrom(sender, address(this), tokenId);
// 保存指定的nft的信息, 这里不保存Matter信息,因为不知到Matter是否转移成功
// _saveMatter(sender, metaMatterId, tokenId);
return tokenId;
}
// 把指定的nft转移给指定的用户
function withdraw(
address to,
uint256 metaMatterId,
uint256 tokenId
) public returns (uint256) {
// 获取erc721指定的合约地址
address tokenContract = ownerOf(metaMatterId);
require(tokenContract != address(0), "metaMatter not exist");
address sender = _msgSender();
// 判断当前用户是否有权限转移
MatterMeta[] memory ownMatters = matterOf(sender);
bool isVerifyed = false;
uint256 resultIdx = 0;
for (uint256 i = 0; i < ownMatters.length; i++) {
if (
ownMatters[i].id == metaMatterId &&
ownMatters[i].tokenId == tokenId
) {
isVerifyed = true;
resultIdx = i;
}
}
require(isVerifyed, "you have no permission to withdraw");
IERC721 token = IERC721(tokenContract);
// 将tokenId存入合约中
token.safeTransferFrom(address(this), to, tokenId);
// 移除指定的nft
_deleteMatter(sender, metaMatterId, tokenId);
return tokenId;
}
// 提到自己的账户中
function withdraw(uint256 metaMatterId, uint256 tokenId)
public
returns (uint256)
{
address sender = _msgSender();
return withdraw(sender, metaMatterId, tokenId);
}
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external returns (bytes4) {
address tokenContract = _msgSender();
uint256 metaMatterId = _metaMatterIds[tokenContract];
// 保存指定的nft的信息,保证NFT转移成功后再存入当前的token
_saveMatter(from, metaMatterId, tokenId);
return 0x150b7a02;
}
function compose(
uint256 yinId,
uint256 yinTid,
uint256 yangId,
uint256 yangTid
) public returns (uint256) {
// 判断当前发送者是否有足够的matter
address sender = _msgSender();
require(_tokenOwners[sender].length > 0, "no matter to compose");
MatterMeta[] memory ownerMatters = _tokenOwners[sender];
MatterMeta[2] memory inputs = [
MatterMeta(yinId, yinTid),
MatterMeta(yangId, yangTid)
];
uint256 counter = 0;
// 检查是否有不合法的matter
for (uint256 i = 0; i < inputs.length; i++) {
for (uint256 j = 0; j < ownerMatters.length; j++) {
if (
inputs[i].id == ownerMatters[j].id &&
inputs[i].tokenId == ownerMatters[j].tokenId
) {
counter += 1;
}
}
}
// 确保所有的matter都是合法的
require(counter == 2, "invalid matter");
// 创建合成的matter,并存入到合约中
IMatter matter = IMatter(_matterNFTContract); // matter合约
// 自增id, 开始铸造
uint256 matterId = matter.mint(
address(this),
yinId,
yinTid,
yangId,
yangTid
);
uint256 removeCount = 0;
// 移除被合成的matter
for (uint256 i = 0; i < inputs.length; i++) {
for (uint256 j = 0; j < ownerMatters.length; j++) {
if (
inputs[i].id == ownerMatters[j].id &&
inputs[i].tokenId == ownerMatters[j].tokenId
) {
// 删除被合成的matter
_deleteMatter(sender, inputs[i].id, inputs[i].tokenId);
removeCount += 1;
// delete ownerMatters[j];
break;
}
}
}
require(removeCount == 2, "make sure remove yin yang");
uint256 matterContractId = getMetaMatterId(_matterNFTContract);
// 保存新的matter给铸造者
_saveMatter(sender, matterContractId, matterId);
// 完成所有操作后返回合成的matter的id
return matterId;
}
function merge(address yin, uint256 yinTid, address yang, uint256 yangTid) public returns(uint256) {
require(yin != address(0) && yang != address(0), "yin and yang not emputy!");
uint256 yinId = getMetaMatterId(yin);
// 把对应的nft质押到合约中
deposit(yinId, yinTid);
uint256 yangId = getMetaMatterId(yang);
// 把对应的nft质押到合约中
deposit(yangId, yangTid);
uint256 newTokenId = compose(yinId, yinTid, yangId, yangTid);
// 把新的token提取到自己的账户
uint256 matterContractId = getMetaMatterId(_matterNFTContract);
withdraw(matterContractId, newTokenId);
return newTokenId;
}
// // 用指定的matter进行合并
// function compose(uint256[] memory matters)
// public
// onlyOwner
// returns (uint256)
// {
// // // 判断当前发送者是否有足够的matter
// // address sender = _msgSender();
// // require(_tokenOwners[sender].length > 0, "no matter to compose");
// // MatterMeta[] memory ownerMatters = _tokenOwners[sender];
// // uint256 counter = 0;
// // // 检查是否有不合法的matter
// // for (uint256 i = 0; i < matters.length; i++) {
// // for (uint256 j = 0; j < ownerMatters.length; j++) {
// // if (matters[i].id == ownerMatters[j].id && matters[i].tokenId == ownerMatters[j].tokenId) {
// // counter += 1;
// // }
// // }
// // }
// // // 确保所有的matter都是合法的
// // require(counter == matters.length, "invalid matter");
// // // 创建合成的matter,并存入到合约中
// // IERC721 matter = IERC721(address(0x0fC5025C764cE34df352757e82f7B5c4Df39A836)); // matter合约
// // // 自增id, 开始铸造
// // // uint256 matterId = matter.mint(address(this), yinId, yinTid, yangId, yangTid);
// // // 移除被合成的matter
// // for (uint256 i = 0; i < matters.length; i++) {
// // for (uint256 j = 0; j < ownerMatters.length; j++) {
// // if (matters[i].id == ownerMatters[j].id && matters[i].tokenId == ownerMatters[j].tokenId) {
// // ownerMatters.remove(j);
// // break;
// // }
// // }
// // }
// // // 完成所有操作后返回合成的matter的id
// // return matterId;
// }
// 分解指定的物质
function deCompose(uint256 tokenId) public returns (uint256, uint256, uint256, uint256) {
// 判断当前发送者是否有足够的matter
address sender = _msgSender();
require(_tokenOwners[sender].length > 0, "no matter to decompose");
uint256 matterId = getMetaMatterId(_matterNFTContract);
uint256 counter = 0;
// 检查是否有不合法的matter
for (uint256 i = 0; i < _tokenOwners[sender].length; i++) {
// 第一个原Matter是matter合约
if (
_tokenOwners[sender][i].tokenId == tokenId &&
_tokenOwners[sender][i].id == matterId
) {
counter += 1;
}
}
require(counter == 1, "invalid matter");
// 从自身的存储中移除
_deleteMatter(sender, matterId, tokenId);
// 获取合约地址
IMatter matter = IMatter(_matterNFTContract); // matter合约
uint256 yangId = matter.getYangId(tokenId);
uint256 yangTid = matter.getYangTid(tokenId);
uint256 yinId = matter.getYinId(tokenId);
uint256 yinTid = matter.getYinTid(tokenId);
// 合成的matter不能为0
require(
yangId != 0 && yangTid != 0 && yinId != 0 && yinTid != 0,
"invalid matter"
);
// 销毁当前的matter
matter.burn(tokenId);
// 恢复对拆分后的matter的控制权
_saveMatter(sender, yangId, yangTid);
_saveMatter(sender, yinId, yinTid);
// 把阴阳转移给发送者的存储中
return (yinId, yinTid, yangId, yangTid);
}
// 分解指定的物质
function demerge(uint256 tokenId) public returns (uint256) {
require(tokenId > 0, "tokenId not null");
uint256 matterContractId = getMetaMatterId(_matterNFTContract);
deposit(matterContractId, tokenId);
(uint256 yinId, uint256 yinTid, uint256 yangId, uint256 yangTid) = deCompose(tokenId);
withdraw(yinId, yinTid);
withdraw(yangId, yangTid);
return tokenId;
}
// 重写合约方法,生成的token防止被转移走
function transferFrom(
address from,
address to,
uint256 tokenId
) public override onlyOwner {
_beforeMatterTransfer();
return super.transferFrom(from, to, tokenId);
}
// 重写合约方法,生成的token防止被转移走
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override onlyOwner {
_beforeMatterTransfer();
return super.safeTransferFrom(from, to, tokenId);
}
// 重写合约方法,生成的token防止被转移走
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata _data
) public override onlyOwner {
_beforeMatterTransfer();
return super.safeTransferFrom(from, to, tokenId, _data);
}
}
|
任何人都可以存入自己的nft到合约中 获取erc721指定的合约地址 将tokenId存入合约中 保存指定的nft的信息, 这里不保存Matter信息,因为不知到Matter是否转移成功 _saveMatter(sender, metaMatterId, tokenId);
|
function deposit(uint256 metaMatterId, uint256 tokenId)
public
returns (uint256)
{
address tokenContract = ownerOf(metaMatterId);
address sender = _msgSender();
IERC721 token = IERC721(tokenContract);
token.safeTransferFrom(sender, address(this), tokenId);
return tokenId;
}
| 14,084,159
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./IHouseGame.sol";
import "./ICash.sol";
import "./IRandomizer.sol";
import "./IRewardPool.sol";
contract Agent is Initializable, OwnableUpgradeable, IERC721ReceiverUpgradeable, PausableUpgradeable {
// struct to store a stake's token, owner, and earning values
struct Stake {
uint8 tenantRating;
uint16 tokenId;
uint256 value;
address owner;
}
event TokenStaked(address owner, uint256 tokenId, bool isHouse, uint256 value);
event HouseClaimed(uint256 tokenId, uint256 earned, bool unstaked);
event BuildingClaimed(uint256 tokenId, uint256 earned, bool unstaked);
// reference to the HouseGame, $CASH and rewards contracts
IHouseGame public house;
ICASH public cash;
IRewardPool public rewardPool;
// maps tokenId to stake
mapping(uint256 => Stake) public agent;
// maps tokenId to Building stakes
mapping(uint256 => Stake) public pack;
// total building staked
uint256 public totalBuildingStaked;
// any rewards distributed when no Building are staked
uint256 public unaccountedRewards;
// amount of $CASH due for staked
uint256 public totalReceivedBuidingTax;
// House must have 3 days worth of $CASH to unstake or else it's too cold
uint256 public constant MINIMUM_TO_EXIT = 3 days;
// Building take a 25% tax on all $CASH claimed
uint256 public constant BUILDING_CLAIM_TAX_PERCENTAGE = 25;
// number of House staked in the Agent
uint256 public totalHouseStaked;
// the last time $CASH was claimed
uint256 private lastClaimTimestamp;
// emergency rescue to allow unstaking without any checks but without $CASH
bool public rescueEnabled;
IRandomizer public randomizer;
/**
* @param _house reference to the House NFT contract
* @param _cash reference to the $CASH token
*/
function initialize(address _house, address _cash, address _randomizer) external initializer {
OwnableUpgradeable.__Ownable_init();
PausableUpgradeable.__Pausable_init();
house = IHouseGame(_house);
cash = ICASH(_cash);
randomizer = IRandomizer(_randomizer);
rescueEnabled = false;
}
/** STAKING */
/**
* adds House and Building to the Agent and Pack
* @param account the address of the staker
* @param tokenIds the IDs of the House and Building to stake
*/
function addManyToAgentAndPack(address account, uint16[] calldata tokenIds) external {
require(account == _msgSender() || _msgSender() == address(house), "DONT GIVE YOUR TOKENS AWAY");
require(tokenIds.length > 0, "No token to stake");
for (uint i = 0; i < tokenIds.length; i++) {
if (_msgSender() != address(house)) {
require(house.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN");
house.transferFrom(_msgSender(), address(this), tokenIds[i]);
} else if (tokenIds[i] == 0) {
continue;
}
if (isHouse(tokenIds[i]))
_addHouseToAgent(account, tokenIds[i]);
else
_addBuildingToPack(account, tokenIds[i]);
}
}
/**
* adds a single House to the Agent
* @param account the address of the staker
* @param tokenId the ID of the House to add to the Agent
*/
function _addHouseToAgent(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
uint8 _random = uint8(randomizer.random(tokenId) % 10 + 1);
agent[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: block.timestamp, // solhint-disable-line not-rely-on-time
tenantRating: _random
});
totalHouseStaked += 1;
emit TokenStaked(account, tokenId, true, block.timestamp); // solhint-disable-line not-rely-on-time
}
/**
* adds a single Building to the Pack
* @param account the address of the staker
* @param tokenId the ID of the Building to add to the Pack
*/
function _addBuildingToPack(address account, uint256 tokenId) internal {
pack[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: totalReceivedBuidingTax,
tenantRating : 0
});
totalBuildingStaked += 1;
emit TokenStaked(account, tokenId, false, totalReceivedBuidingTax);
}
/** CLAIMING / UNSTAKING */
/**
* realize $CASH earnings and optionally unstake tokens from the Agent / Pack
* to unstake a House it will require it has 3 days worth of $CASH unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
* @param burn unstake ALL of the tokens then burn all listed in tokenIds
*/
function claimManyFromAgentAndPack(uint16[] calldata tokenIds, bool unstake, bool burn) external whenNotPaused _updateEarnings {
require(tokenIds.length > 0, "No token to claim");
if(burn) {
require(unstake, "burn only when unstake");
}
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isHouse(tokenIds[i]))
owed += _claimHouseFromAgent(tokenIds[i], unstake);
else
owed += _claimBuildingFromPack(tokenIds[i], unstake);
}
if (owed == 0) return;
if (unstake && burn) {
rewardPool.payTax(_msgSender(), owed);
return;
}
cash.mint(_msgSender(), owed);
}
/**
* realize $CASH earnings for a single House and optionally unstake it
* if not unstaking, pay a 25% tax to the staked Building
* @param tokenId the ID of the House to claim earnings from
* @param unstake whether or not to unstake the House
* @return owed - the amount of $CASH earned
*/
function _claimHouseFromAgent(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake storage stake = agent[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT THREE DAY'S CASH"); // solhint-disable-line not-rely-on-time, reason-string
if (stake.value > lastClaimTimestamp) {
owed = 0; // $CASH production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * house.getIncomePerDay(tokenId) / 1 days;
}
uint256 _random = randomizer.random(tokenId) % 100 + 1;
uint256 tax = owed * BUILDING_CLAIM_TAX_PERCENTAGE / 100;
_payBuildingTax(tax); // percentage tax to staked building
owed -= tax; // remainder goes to House owner
if (_random > stake.tenantRating * 10) {
owed = _propertyDamageTax(owed, house.getPropertyDamage(tokenId));
}
if (unstake) {
_random = randomizer.random(tokenId) % 100 + 1;
if (_random > stake.tenantRating * 10) {
_payBuildingTax(owed);
owed = 0;
}
house.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back House
delete agent[tokenId];
totalHouseStaked -= 1;
} else {
stake.value = block.timestamp; // solhint-disable-line not-rely-on-time
}
emit HouseClaimed(tokenId, owed, unstake);
}
/**
* realize $CASH earnings for a single Building and optionally unstake it
* Building earn $CASH proportional to their Alpha rank
* @param tokenId the ID of the Building to claim earnings from
* @param unstake whether or not to unstake the Building
* @return owed - the amount of $CASH earned
*/
function _claimBuildingFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(house.ownerOf(tokenId) == address(this), "you're not part of this!");
Stake memory stake = pack[tokenId];
require(stake.owner == _msgSender(), "no stealing here");
owed = totalReceivedBuidingTax - stake.value;
if (unstake) {
totalBuildingStaked--;
house.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Building
delete pack[tokenId];
} else {
pack[tokenId].value = totalReceivedBuidingTax;
}
emit BuildingClaimed(tokenId, owed, unstake);
}
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
require(tokenIds.length > 0, "No token to rescue");
uint256 tokenId;
Stake memory stake;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isHouse(tokenId)) {
stake = agent[tokenId];
require(stake.owner == _msgSender(), "no stealing here");
house.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back House
delete agent[tokenId];
totalHouseStaked -= 1;
emit HouseClaimed(tokenId, 0, true);
} else {
stake = pack[tokenId];
require(stake.owner == _msgSender(), "no stealing here");
totalBuildingStaked -= 1;
house.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Building
delete pack[tokenId];
emit BuildingClaimed(tokenId, 0, true);
}
}
}
/** ACCOUNTING */
/**
* add $CASH to claimable pot for the Pack
* @param amount $CASH to add to the pot
*/
function _payBuildingTax(uint256 amount) internal {
if (totalBuildingStaked == 0) { // if there's no staked building
unaccountedRewards += amount; // keep track of $CASH due to building
return;
}
// makes sure to include any unaccounted $CASH
totalReceivedBuidingTax += (amount + unaccountedRewards) / totalBuildingStaked;
unaccountedRewards = 0;
}
function _propertyDamageTax(uint256 amount, uint256 _propertyDamage) internal pure returns(uint256) {
return amount * (100 - _propertyDamage) / 100;
}
/**
* tracks $CASH earnings to ensure it stops once 2.4 billion is eclipsed
*/
modifier _updateEarnings() {
lastClaimTimestamp = block.timestamp; // solhint-disable-line not-rely-on-time
_;
}
/** ADMIN */
function setContracts(address _randomizer, address _rewardPool) external onlyOwner {
require(_randomizer != address(0) && _rewardPool != address(0), "Invalid contract address");
randomizer = IRandomizer(_randomizer);
rewardPool = IRewardPool(_rewardPool);
}
/**
* allows owner to enable "rescue mode"
* simplifies accounting, prioritizes tokens out in emergency
*/
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
/**
* enables owner to pause / unpause minting
*/
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** READ ONLY */
/**
* checks if a token is a House
* @param tokenId the ID of the token to check
* @return _house - whether or not a token is a House
*/
function isHouse(uint256 tokenId) public view returns (bool _house) {
_house = house.getTokenTraits(tokenId).isHouse;
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Agent directly"); // solhint-disable-line reason-string
return IERC721ReceiverUpgradeable.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
interface IHouseGame is IERC721Upgradeable {
function getPropertyDamage(uint256 tokenId)
external
view
returns (uint256 _propertyDamage);
function getIncomePerDay(uint256 tokenId)
external
view
returns (uint256 _incomePerDay);
function getHousePaidTokens() external view returns (uint256);
function getBuildingPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId)
external
view
returns (HouseBuilding memory);
// struct to store each token's traits
struct HouseBuilding {
bool isHouse;
uint8 model;
uint256 imageId;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
interface ICASH is IERC20{
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.4;
interface IRandomizer {
function random(uint256 seed) external view returns (uint256);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.4;
interface IRewardPool {
function payTax(address account, uint256 burnAmount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
|
struct to store each token's traits
|
interface IHouseGame is IERC721Upgradeable {
function getPropertyDamage(uint256 tokenId)
external
view
returns (uint256 _propertyDamage);
function getIncomePerDay(uint256 tokenId)
external
view
returns (uint256 _incomePerDay);
function getHousePaidTokens() external view returns (uint256);
function getBuildingPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId)
external
view
returns (HouseBuilding memory);
struct HouseBuilding {
bool isHouse;
uint8 model;
uint256 imageId;
}
}
| 6,861,341
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/ERC20.sol";
/**
* @title PineappleToke
* @author Asvoria Kuan<asvoria@live.com>
* @dev Use solidity compiler version 0.8.1
*/
contract PINE is ERC20 {
enum stages {
STAGE_INIT,
STAGE_FUNDING,
STAGE_GRACE,
STAGE_REPAYMENT,
STAGE_END
}
// This is the current stage.
stages public CURENT_STAGE = stages.STAGE_INIT;
int[] public interest_rates = [-20,-10,0,10,20];
string public token_name = "PineappleToken"; //Generated
string public token_symbol = "PINE"; //Generated
uint256 public token_borrow = 1000; //User key in data, this will be multiplied
uint256 public loan_duration = 1095 days; //User key in data, 3 years
uint256 public loan_payment_duration = 3650 days; //User key in data, 10 years
uint public loan_payment_count = loan_payment_duration / 30;
uint public loan_payment_count_num;
uint256 public tokenBuyRate = 1;
//1 ether = 1,000,000,000,000,000,000 wei (10^18)
uint256 public tokenPrice = 0.000001 ether; //Fix
uint256 public initial_token_supply = 1e18; //Fix
uint256 public INITIAL_SUPPLY = initial_token_supply * token_borrow;
address payable public borrower;
address payable public ownerAdds; //User key in data
address payable public tokenWallet; //Generated
uint256 public ICOStartTime = block.timestamp;
uint256 public ICOEndTime = block.timestamp + loan_duration;
bool public ICOCompleted;
uint256 public RepaymentStartTime;
uint256 public monthlySalary = 0;
address[] public lenders;
address[] public borrowers;
uint256[] public payment_principal;
// modifier
modifier atStage(stages _stage) {
require(
CURENT_STAGE == _stage,
"Function cannot be called at this time."
);
_;
}
modifier whenIcoCompleted{
require(ICOCompleted);
_;
}
modifier onlyCrowdsale{
require(block.timestamp < ICOEndTime && block.timestamp > ICOStartTime);
_;
}
modifier onlyOwner{
require(msg.sender == ownerAdds);
_;
}
modifier afterCrowdsale{
require(block.timestamp > ICOEndTime);
_;
}
modifier repaymentPeriod{
require(block.timestamp > RepaymentStartTime);
_;
}
// function
function nextStage() internal {
CURENT_STAGE = stages(uint(CURENT_STAGE) + 1);
}
function destroy() onlyOwner public {
selfdestruct(ownerAdds);
}
function saveAddress() payable public {
lenders.push(msg.sender);
}
function saveAddressBorrower() payable public {
borrowers.push(msg.sender);
}
//Call function to start repayment period
function startRepayment(
uint256 _monthlySalary
) public onlyOwner afterCrowdsale returns(bool){
RepaymentStartTime = block.timestamp;
loan_payment_count_num = 0;
monthlySalary = _monthlySalary * (1 ether); //when input, it is in wei
_burn(ownerAdds, balanceOf(ownerAdds)); //When start repayment, burn all leftover tokens remained in borrower account
//calculate payment_principal
for (uint i=0; i<lenders.length; i++) {
address payable makePayAdd = payable(address(uint160(lenders[i])));
payment_principal[i] = balanceOf(makePayAdd)/(loan_payment_count);
}
return true;
}
//Can only start to distribute interest after the repayment period started
//interests is distributed according to lenders token ownership
function distributeInterest() public payable onlyOwner afterCrowdsale repaymentPeriod{
//Interest is 5%per anum of monthly reported salary. monthlySalary
require(monthlySalary > 0);
uint256 InterestRate = (monthlySalary/100)* (5)/(INITIAL_SUPPLY);
uint256 InterestCalc = 0 ether;
for (uint i=0; i<lenders.length; i++) {
address payable makePayAdd = payable(address(uint160(lenders[i])));
InterestCalc = balanceOf(makePayAdd) * (InterestRate);
require (InterestCalc > 0, "Amount is less than the minimum value");
require (msg.sender.balance >= InterestCalc, "Contract balance is empty");
makePayAdd.transfer(InterestCalc); //ether must be in contract balance
}
}
function Repayment() public payable onlyOwner afterCrowdsale repaymentPeriod {
uint256 tokensRepay;
uint256 tokensRepayEther = 0 ether;
for (uint i=0; i<lenders.length; i++) {
address payable makePayAdd = payable(address(uint160(lenders[i])));
tokensRepay = payment_principal[i];
tokensRepayEther = tokensRepay*(tokenPrice);
require (tokensRepayEther > 0, "Amount is less than the minimum value");
require (msg.sender.balance >= tokensRepayEther, "Contract balance is empty");
makePayAdd.transfer(tokensRepayEther); //ether must be in contract balance
transferFrom(makePayAdd,msg.sender,tokensRepay);
_burn(makePayAdd, payment_principal[i]);
}
loan_payment_count_num++;
}
function buyTokens(address debtAdds) public payable onlyCrowdsale{
address payable token_Wallet = payable(debtAdds);
require(msg.sender != address(0));
require(balanceOf(token_Wallet) > 0);
uint256 etherUsed = uint256(msg.value);
require(etherUsed > 0);
uint256 tokensToBuy = etherUsed/(tokenBuyRate);
// Return extra ether when tokensToBuy > balances[tokenWallet]
if(tokensToBuy > balanceOf(token_Wallet)){
uint256 exceedingTokens = tokensToBuy - (balanceOf(token_Wallet));
uint256 exceedingEther = 0 ether;
exceedingEther = exceedingTokens * (tokenBuyRate);
payable(msg.sender).transfer(exceedingEther);
tokensToBuy = tokensToBuy - (exceedingTokens);
etherUsed = etherUsed - (exceedingEther);
}
transferFrom(token_Wallet,msg.sender,uint256(tokensToBuy));
payable(token_Wallet).transfer(etherUsed);
saveAddress();
}
function depositContract() public payable onlyOwner afterCrowdsale repaymentPeriod{
require(msg.sender != address(0));
require(balanceOf(tokenWallet) > 0);
}
function emergencyExtract() external payable onlyOwner{
ownerAdds.transfer(address(this).balance);
}
function borrowerMint(uint256 tokensBorrowed) public payable {
borrower = payable(msg.sender);
tokenWallet = borrower;
_mint(borrower, (tokensBorrowed));
saveAddressBorrower();
}
function checkBorrower() public view returns(bool){
address checkAdds = msg.sender;
for (uint i=0; i<borrowers.length; i++) {
if(checkAdds==borrowers[i]){
//found match
return true;
}
}
return false;
}
constructor() ERC20(token_name,token_symbol){
}
}
|
Return extra ether when tokensToBuy > balances[tokenWallet]
|
function buyTokens(address debtAdds) public payable onlyCrowdsale{
address payable token_Wallet = payable(debtAdds);
require(msg.sender != address(0));
require(balanceOf(token_Wallet) > 0);
uint256 etherUsed = uint256(msg.value);
require(etherUsed > 0);
uint256 tokensToBuy = etherUsed/(tokenBuyRate);
if(tokensToBuy > balanceOf(token_Wallet)){
uint256 exceedingTokens = tokensToBuy - (balanceOf(token_Wallet));
uint256 exceedingEther = 0 ether;
exceedingEther = exceedingTokens * (tokenBuyRate);
payable(msg.sender).transfer(exceedingEther);
tokensToBuy = tokensToBuy - (exceedingTokens);
etherUsed = etherUsed - (exceedingEther);
}
transferFrom(token_Wallet,msg.sender,uint256(tokensToBuy));
payable(token_Wallet).transfer(etherUsed);
saveAddress();
}
| 12,543,083
|
//SPDX-License-Identifier: MIT OR Apache2.0
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract NFTMarket1 is ReentrancyGuard, IERC721Receiver{
using Counters for Counters.Counter;
Counters.Counter private _itemIds;
address public constant marketOwner = 0x778eb5AEA11c8F0f2BC2280ce0305cD61B3D3714;
address private erc20token = 0xc2112100B1392958D462A1813799E2C54Aa1Affc;
//address payable marketOwner;
uint256 listingPrice;
constructor(){
//marketOwner = payable(msg.sender);
listingPrice = 0.025 ether;
}
struct MarketItem{
uint itemId;
uint tokenId;
address nftContract;
address payable owner;
address lastSeller;
address[] prevOwners;
uint price;
uint lastPrice;
bool onSale;
}
mapping(uint256 => MarketItem) private idToMarketItem;
function createMarketItem(
uint256 tokenId,
address nftContract
) public returns(uint256){
require(IERC721(nftContract).ownerOf(tokenId) == msg.sender, 'Only owner can list new Items');
_itemIds.increment();
uint itemId = _itemIds.current();
address[] memory prevOwners;
idToMarketItem[itemId] = MarketItem(
itemId,
tokenId,
nftContract,
payable(msg.sender),
payable(address(0)),
prevOwners,
0,
0,
false
);
return itemId;
}
function listItemOnSale(
uint itemId,
address nftContract,
uint price
) public payable{
require(idToMarketItem[itemId].owner == msg.sender, 'only owner can put this item on sale');
//require(msg.value == listingPrice, "Amount doesn't meet listing fees requirements (.0025eth)");
IERC721(nftContract).safeTransferFrom(msg.sender, address(this), idToMarketItem[itemId].tokenId);
//payable(marketOwner).transfer(msg.value);
idToMarketItem[itemId].onSale = true;
idToMarketItem[itemId].lastSeller = msg.sender;
idToMarketItem[itemId].price = price;
}
function sellMarketItem(
uint itemId,
address nftContract
) public payable nonReentrant{
/*
//require(msg.value == idToMarketItem[itemId].price, "Amount must be equal to price");
require(IERC20(erc20token).balanceOf(msg.sender) >= idToMarketItem[itemId].price, "Amount must be equal to price");
require(msg.sender != idToMarketItem[itemId].owner, "Owner shouldn't buy their NFTs");
IERC721(nftContract).safeTransferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
//idToMarketItem[itemId].owner.transfer(msg.value);
//IERC20(erc20token).transferFrom(msg.sender, address(this),idToMarketItem[itemId].price);
//IERC20(erc20token).transfer(idToMarketItem[itemId].owner,idToMarketItem[itemId].price);
IERC20(erc20token).transferFrom(msg.sender, idToMarketItem[itemId].owner, idToMarketItem[itemId].price);
idToMarketItem[itemId].prevOwners.push(idToMarketItem[itemId].owner) ;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].lastPrice = idToMarketItem[itemId].price;
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].onSale = false;
*/
require(msg.value == idToMarketItem[itemId].price, "Amount must be equal to price");
//require(IERC20(erc20token).balanceOf(msg.sender) >= idToMarketItem[itemId].price, "Amount must be equal to price");
require(msg.sender != idToMarketItem[itemId].owner, "Owner shouldn't buy their NFTs");
IERC721(nftContract).safeTransferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
idToMarketItem[itemId].owner.transfer(msg.value);
//IERC20(erc20token).transferFrom(msg.sender, address(this),idToMarketItem[itemId].price);
//IERC20(erc20token).transfer(idToMarketItem[itemId].owner,idToMarketItem[itemId].price);
idToMarketItem[itemId].prevOwners.push(idToMarketItem[itemId].owner) ;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].lastPrice = idToMarketItem[itemId].price;
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].onSale = false;
}
function fetchAllItemsOnSale() public view returns(MarketItem[] memory){
uint itemsCount = _itemIds.current();
uint onSaleItems = 0;
for(uint i = 0; i < itemsCount; i++){
if(idToMarketItem[i+1].onSale == true){
onSaleItems++;
}
}
MarketItem[] memory marketItems = new MarketItem[](onSaleItems);
uint index = 0;
for(uint i = 0; i<itemsCount; i++){
if(idToMarketItem[i+1].onSale == true){
MarketItem storage currentItem = idToMarketItem[i+1];
marketItems[index] = currentItem;
index++;
}
}
return marketItems;
}
function fetchAllItemsOfOwner(address owner) public view returns(MarketItem[] memory){
uint itemsCount = _itemIds.current();
uint ownedItems = 0;
for(uint i = 0; i < itemsCount; i++){
if(idToMarketItem[i+1].owner == owner && !idToMarketItem[i+1].onSale){
ownedItems++;
}
}
MarketItem[] memory marketItems = new MarketItem[](ownedItems);
uint index = 0;
for(uint i = 0; i<itemsCount; i++){
if(idToMarketItem[i+1].owner == owner && !idToMarketItem[i+1].onSale){
MarketItem storage currentItem = idToMarketItem[i+1];
marketItems[index] = currentItem;
index++;
}
}
return marketItems;
}
// Add retrieve all my NFTs
function fetchAllItems() public view returns(MarketItem[] memory){
uint itemsCount = _itemIds.current();
MarketItem[] memory marketItems = new MarketItem[](itemsCount);
for(uint i = 0; i < itemsCount; i++){
MarketItem storage currentItem = idToMarketItem[i+1];
marketItems[i] = currentItem;
}
return marketItems;
}
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external override pure returns (bytes4){
operator;
from;
tokenId;
data;
return 0x150b7a02;
}
}
|
require(msg.value == idToMarketItem[itemId].price, "Amount must be equal to price");idToMarketItem[itemId].owner.transfer(msg.value);IERC20(erc20token).transferFrom(msg.sender, address(this),idToMarketItem[itemId].price);IERC20(erc20token).transfer(idToMarketItem[itemId].owner,idToMarketItem[itemId].price);require(IERC20(erc20token).balanceOf(msg.sender) >= idToMarketItem[itemId].price, "Amount must be equal to price");IERC20(erc20token).transferFrom(msg.sender, address(this),idToMarketItem[itemId].price);IERC20(erc20token).transfer(idToMarketItem[itemId].owner,idToMarketItem[itemId].price);
|
function sellMarketItem(
uint itemId,
address nftContract
) public payable nonReentrant{
require(IERC20(erc20token).balanceOf(msg.sender) >= idToMarketItem[itemId].price, "Amount must be equal to price");
require(msg.sender != idToMarketItem[itemId].owner, "Owner shouldn't buy their NFTs");
IERC721(nftContract).safeTransferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
IERC20(erc20token).transferFrom(msg.sender, idToMarketItem[itemId].owner, idToMarketItem[itemId].price);
idToMarketItem[itemId].prevOwners.push(idToMarketItem[itemId].owner) ;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].lastPrice = idToMarketItem[itemId].price;
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].onSale = false;
require(msg.value == idToMarketItem[itemId].price, "Amount must be equal to price");
require(msg.sender != idToMarketItem[itemId].owner, "Owner shouldn't buy their NFTs");
IERC721(nftContract).safeTransferFrom(address(this), msg.sender, idToMarketItem[itemId].tokenId);
idToMarketItem[itemId].owner.transfer(msg.value);
idToMarketItem[itemId].prevOwners.push(idToMarketItem[itemId].owner) ;
idToMarketItem[itemId].owner = payable(msg.sender);
idToMarketItem[itemId].lastPrice = idToMarketItem[itemId].price;
idToMarketItem[itemId].price = 0;
idToMarketItem[itemId].onSale = false;
}
| 6,401,954
|
./full_match/42/0x47188D3eFb9F454F9b11EE1B17413b98F6Ea0808/sources/mnt/c/projects/nft-aave/contracts/AaveNFTMain.sol
|
This function redeems the caller's shard, transferring in their shard NFT and sending back their accrued rewards and stkAAVE. This is only call-able by the shard owner, and cannot be called if they are the ONLY owner. Requires approval from the shard contract./
|
function redeemShard(uint256 shardId) external {
require(shardContract.ownerOf(shardId) == msg.sender, "AaveNFTMain: Only the shard owner can redeem.");
require(!isOnlyOwner(msg.sender), "AaveNFTMain: Caller is the last shard owner, redeem the main NFT.");
( ,uint256 rewardToClaim) = getAdjustedRewardsBalance(shardId);
stkAave.claimRewards(msg.sender, rewardToClaim);
stkAave.transfer(msg.sender, shardStakes[shardId].stake);
shardStakes[shardId].stake = 0;
}
| 16,279,484
|
./partial_match/97/0x34d7ec1dFcA65397D85FEE04Ac573815A68D75CA/sources/BiscuitMasterChef.sol
|
Add a new lp to the pool. Can only be called by the owner.
|
function add(
IERC20 _lpToken,
BiscuitToken _rewardToken,
uint256 _startBlock,
uint256 _allocPoint,
uint256 _rewardPerBlock,
uint256 _percentLockReward,
uint256 _percentForDev,
uint256 _halvingAfterBlock,
uint256[] memory _rewardMultiplier,
uint256 _lockFromBlock,
uint256 _lockToBlock
) public onlyOwner {
_setAllocPoints(_rewardToken, _allocPoint);
uint256 finishBonusAtBlock = _setHalvingAtBlocks(poolInfo.length, _rewardMultiplier, _halvingAfterBlock, _startBlock);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
rewardToken: _rewardToken,
lastRewardBlock: block.number > _startBlock ? block.number : _startBlock,
allocPoint: _allocPoint,
accRewardPerShare: 0,
startBlock: _startBlock,
rewardPerBlock: _rewardPerBlock,
percentLockReward: _percentLockReward,
percentForDev: _percentForDev,
finishBonusAtBlock: finishBonusAtBlock,
totalLock: 0,
lockFromBlock: _lockFromBlock,
lockToBlock: _lockToBlock
}));
}
| 11,448,633
|
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/contracts/interfaces/types/ProgramInfo.sol
|
Validates and creates a new Program Reverts for invalid programInfos programInfo Un-sanitized static program information/
|
function validate(ProgramInfo memory programInfo) internal view {
if (isStarted(programInfo, block.timestamp)) revert ProgramInvalidStartError();
if (programInfo.duration < MIN_DURATION || programInfo.duration > MAX_DURATION) revert ProgramInvalidDurationError();
}
| 1,912,732
|
pragma solidity ^0.4.19;
import './ERC721.sol';
import './SafeMath.sol';
import './Ownable.sol';
/// 产品生产者
contract ThingFactory is Ownable {
using SafeMath for uint256;
// 生产一个产品后的通知事件
event NewThing(address indexed _from, uint thingId, string name, uint dna);
// 日志事件
event LogStatus(address indexed _from, string log);
// 基因位数
uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;
// 技能冷却时间
uint cooldownTime = 1 days;
struct Thing {
string name; // 名字
uint price; // 价格
uint dna; // DNA
uint32 level; // 等级
uint32 readyTime; // 技能冷却
uint32 generation; // 代数
uint16 winCount; // 战斗胜利次数
uint16 lossCount; // 战斗失败次数
}
Thing[] public things;
// _tokenId <==> _owner
mapping (uint => address) public thingToOwner;
// _owner <==> _tokenCount
mapping (address => uint) ownerThingCount;
function _createThing(string _name, uint _dna, uint32 _generation) internal {
require(msg.sender != address(0));
// 配置默认产品
Thing memory _thing;
_thing.name = _name;
_thing.price = (_dna / 100) % 100;
_thing.dna = _dna;
_thing.level = uint32(1);
_thing.readyTime = uint32(now);
_thing.generation = _generation;
_thing.winCount = uint16(0);
_thing.lossCount = uint16(0);
// 记录到区块链
uint id = things.push(_thing) - 1;
thingToOwner[id] = msg.sender;
ownerThingCount[msg.sender]++;
// 通知事件
NewThing(msg.sender, id, _name, _dna);
}
function _generateRandomDna(string _str) internal view returns (uint) {
uint rand = uint(keccak256(_str));
return rand % dnaModulus;
}
// 对外接口,用于生产产品
function createRandomThing(string _name, uint _limit) public {
require(ownerThingCount[msg.sender] <= _limit);
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createThing(_name, randDna, uint32(0));
}
modifier onlyOwnerOf(uint _thingId) {
require(msg.sender == thingToOwner[_thingId]);
_;
}
function withdraw() external onlyOwner {
owner.transfer(this.balance);
}
// 对外接口,返回相应owner的产品Id数组
function getThingsByOwner(address _owner) external view returns(uint[]) {
uint[] memory result = new uint[](ownerThingCount[_owner]);
uint counter = 0;
for (uint i = 0; i < things.length; i++) {
if (thingToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
// 对外接口,返回对应Id的产品
function getThing(uint _thingId) public view returns (
string name,
uint price,
uint dna,
uint32 level,
uint32 readyTime,
uint32 generation,
uint16 winCount,
uint16 lossCount) {
Thing storage thing = things[_thingId];
name = thing.name;
price = thing.price;
dna = thing.dna;
level = thing.level;
readyTime = thing.readyTime;
generation = thing.generation;
winCount = thing.winCount;
lossCount = thing.lossCount;
}
function _triggerCooldown(Thing storage _thing) internal {
_thing.readyTime = uint32(now + cooldownTime);
}
function _isReady(Thing storage _thing) internal view returns (bool) {
return (_thing.readyTime <= now);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
}
/// 繁育&喂养系统
contract ThingFeedAndBreed is ThingFactory {
function feedAndMultiply(uint _thingId, uint _targetDna, string _species) internal onlyOwnerOf(_thingId) {
Thing storage myThing = things[_thingId];
require(_isReady(myThing));
_targetDna = _targetDna % dnaModulus;
uint newDna = (myThing.dna + _targetDna) / 2;
// 吃了Kitty后,dna最后两个数字设定为99
// 例如:7290459416715799
if (keccak256(_species) == keccak256("kitty")) {
newDna = newDna - newDna % 100 + 99;
}
_createThing(strConcat("n",myThing.name, "", "", ""), newDna, myThing.generation + 1);
_triggerCooldown(myThing);
}
// 喂养
function feedOnKitty(uint _thingId, uint _kittyId) public {
// 使用_kittyId作为kittyDna
uint kittyDna = _kittyId;
// (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
feedAndMultiply(_thingId, kittyDna, "kitty");
}
// 繁育
function breed(uint _thingId, uint _targetThingId) public {
uint _targetDna = things[_targetThingId].dna;
feedAndMultiply(_thingId, _targetDna, "thing");
}
}
/// 升级系统
contract ThingUpgrade is ThingFactory {
// 默认升级费用 1 ETH
uint levelUpFee = 1 ether;
modifier aboveLevel(uint _level, uint _thingId) {
require(things[_thingId].level >= _level);
_;
}
// 设置升级费用
function setLevelUpFee(uint _fee) external onlyOwner {
levelUpFee = _fee;
}
// 升级
function levelUp(uint _thingId) external payable {
require(msg.value == levelUpFee);
things[_thingId].level++;
}
// 2级可以改名
function changeName(uint _thingId, string _newName) external aboveLevel(2, _thingId) onlyOwnerOf(_thingId) {
things[_thingId].name = _newName;
}
// 20级可以定制Dna
function changeDna(uint _thingId, uint _newDna) external aboveLevel(20, _thingId) onlyOwnerOf(_thingId) {
things[_thingId].dna = _newDna;
}
}
/// 对战系统
contract ThingAttack is ThingFactory, ThingFeedAndBreed {
uint randNonce = 0;
// 攻击方将有70%的几率获胜,防守方将有30%的几率获胜
uint attackVictoryProbability = 70;
function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256(now, msg.sender, randNonce)) % _modulus;
}
// 两个产品互相对战
function attack(uint _thingId, uint _targetId) external onlyOwnerOf(_thingId) {
Thing storage myThing = things[_thingId];
Thing storage enemyThing = things[_targetId];
uint rand = randMod(100);
if (rand <= attackVictoryProbability) {
myThing.winCount++;
myThing.level++;
enemyThing.lossCount++;
feedAndMultiply(_thingId, enemyThing.dna, "thing");
} else {
myThing.lossCount++;
enemyThing.winCount++;
_triggerCooldown(myThing);
}
}
}
/// ERC721 Impl
contract ThingCore is ThingAttack, ThingUpgrade, ERC721 {
using SafeMath for uint256;
mapping (uint => address) thingApprovals;
// ERC721 impl
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerThingCount[_owner];
}
// ERC721 impl
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return thingToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownerThingCount[_to] = ownerThingCount[_to].add(1);
ownerThingCount[_from] = ownerThingCount[_from].sub(1);
thingToOwner[_tokenId] = _to;
Transfer(_from, _to, _tokenId);
}
// ERC721 impl
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
_transfer(msg.sender, _to, _tokenId);
}
// ERC721 impl
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
thingApprovals[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// ERC721 impl
function takeOwnership(uint256 _tokenId) public {
require(thingApprovals[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
function buyThing(uint _thingId) public payable {
address owner = thingToOwner[_thingId];
_transfer(owner, msg.sender, _thingId);
}
}
|
喂养 使用_kittyId作为kittyDna (,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
|
function feedOnKitty(uint _thingId, uint _kittyId) public {
uint kittyDna = _kittyId;
feedAndMultiply(_thingId, kittyDna, "kitty");
}
| 915,163
|
pragma solidity 0.6.0;
import "./Lib/Address.sol";
import "./Lib/SafeMath.sol";
import "./Lib/AddressPayable.sol";
import "./Lib/SafeERC20.sol";
/**
* @title NToken contract
* @dev Include standard erc20 method, mining method, and mining data
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Executable contract
interface Nest_3_Implement {
// Execute
function doit() external;
}
// NestNode assignment contract
interface Nest_NodeAssignment {
function bookKeeping(uint256 amount) external;
}
/**
* @title Voting factory + mapping
* @dev Vote creating method
*/
contract Nest_3_VoteFactory {
using SafeMath for uint256;
uint256 _limitTime = 7 days; // Vote duration
uint256 _NNLimitTime = 1 days; // NestNode raising time
uint256 _circulationProportion = 51; // Proportion of votes to pass
uint256 _NNUsedCreate = 10; // The minimum number of NNs to create a voting contract
uint256 _NNCreateLimit = 100; // The minimum number of NNs needed to start voting
uint256 _emergencyTime = 0; // The emergency state start time
uint256 _emergencyTimeLimit = 3 days; // The emergency state duration
uint256 _emergencyNNAmount = 1000; // The number of NNs required to switch the emergency state
ERC20 _NNToken; // NestNode Token
ERC20 _nestToken; // NestToken
mapping(string => address) _contractAddress; // Voting contract mapping
mapping(address => bool) _modifyAuthority; // Modify permissions
mapping(address => address) _myVote; // Personal voting address
mapping(address => uint256) _emergencyPerson; // Emergency state personal voting number
mapping(address => bool) _contractData; // Voting contract data
bool _stateOfEmergency = false; // Emergency state
address _destructionAddress; // Destroy contract address
event ContractAddress(address contractAddress);
/**
* @dev Initialization method
*/
constructor () public {
_modifyAuthority[address(msg.sender)] = true;
}
/**
* @dev Reset contract
*/
function changeMapping() public onlyOwner {
_NNToken = ERC20(checkAddress("nestNode"));
_destructionAddress = address(checkAddress("nest.v3.destruction"));
_nestToken = ERC20(address(checkAddress("nest")));
}
/**
* @dev Create voting contract
* @param implementContract The executable contract address for voting
* @param nestNodeAmount Number of NNs to pledge
*/
function createVote(address implementContract, uint256 nestNodeAmount) public {
require(address(tx.origin) == address(msg.sender), "It can't be a contract");
require(nestNodeAmount >= _NNUsedCreate);
Nest_3_VoteContract newContract = new Nest_3_VoteContract(implementContract, _stateOfEmergency, nestNodeAmount);
require(_NNToken.transferFrom(address(tx.origin), address(newContract), nestNodeAmount), "Authorization transfer failed");
_contractData[address(newContract)] = true;
emit ContractAddress(address(newContract));
}
/**
* @dev Use NEST to vote
* @param contractAddress Vote contract address
*/
function nestVote(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_contractData[contractAddress], "It's not a voting contract");
require(!checkVoteNow(address(msg.sender)));
Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress);
newContract.nestVote();
_myVote[address(tx.origin)] = contractAddress;
}
/**
* @dev Vote using NestNode Token
* @param contractAddress Vote contract address
* @param NNAmount Amount of NNs to pledge
*/
function nestNodeVote(address contractAddress, uint256 NNAmount) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_contractData[contractAddress], "It's not a voting contract");
Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress);
require(_NNToken.transferFrom(address(tx.origin), address(newContract), NNAmount), "Authorization transfer failed");
newContract.nestNodeVote(NNAmount);
}
/**
* @dev Excecute contract
* @param contractAddress Vote contract address
*/
function startChange(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_contractData[contractAddress], "It's not a voting contract");
Nest_3_VoteContract newContract = Nest_3_VoteContract(contractAddress);
require(_stateOfEmergency == newContract.checkStateOfEmergency());
addSuperManPrivate(address(newContract));
newContract.startChange();
deleteSuperManPrivate(address(newContract));
}
/**
* @dev Switch emergency state-transfer in NestNode Token
* @param amount Amount of NNs to transfer
*/
function sendNestNodeForStateOfEmergency(uint256 amount) public {
require(_NNToken.transferFrom(address(tx.origin), address(this), amount));
_emergencyPerson[address(tx.origin)] = _emergencyPerson[address(tx.origin)].add(amount);
}
/**
* @dev Switch emergency state-transfer out NestNode Token
*/
function turnOutNestNodeForStateOfEmergency() public {
require(_emergencyPerson[address(tx.origin)] > 0);
require(_NNToken.transfer(address(tx.origin), _emergencyPerson[address(tx.origin)]));
_emergencyPerson[address(tx.origin)] = 0;
uint256 nestAmount = _nestToken.balanceOf(address(this));
require(_nestToken.transfer(address(_destructionAddress), nestAmount));
}
/**
* @dev Modify emergency state
*/
function changeStateOfEmergency() public {
if (_stateOfEmergency) {
require(now > _emergencyTime.add(_emergencyTimeLimit));
_stateOfEmergency = false;
_emergencyTime = 0;
} else {
require(_emergencyPerson[address(msg.sender)] > 0);
require(_NNToken.balanceOf(address(this)) >= _emergencyNNAmount);
_stateOfEmergency = true;
_emergencyTime = now;
}
}
/**
* @dev Check whether participating in the voting
* @param user Address to check
* @return bool Whether voting
*/
function checkVoteNow(address user) public view returns (bool) {
if (_myVote[user] == address(0x0)) {
return false;
} else {
Nest_3_VoteContract vote = Nest_3_VoteContract(_myVote[user]);
if (vote.checkContractEffective() || vote.checkPersonalAmount(user) == 0) {
return false;
}
return true;
}
}
/**
* @dev Check my voting
* @param user Address to check
* @return address Address recently participated in the voting contract address
*/
function checkMyVote(address user) public view returns (address) {
return _myVote[user];
}
// Check the voting time
function checkLimitTime() public view returns (uint256) {
return _limitTime;
}
// Check the NestNode raising time
function checkNNLimitTime() public view returns (uint256) {
return _NNLimitTime;
}
// Check the voting proportion to pass
function checkCirculationProportion() public view returns (uint256) {
return _circulationProportion;
}
// Check the minimum number of NNs to create a voting contract
function checkNNUsedCreate() public view returns (uint256) {
return _NNUsedCreate;
}
// Check the minimum number of NNs raised to start a vote
function checkNNCreateLimit() public view returns (uint256) {
return _NNCreateLimit;
}
// Check whether in emergency state
function checkStateOfEmergency() public view returns (bool) {
return _stateOfEmergency;
}
// Check the start time of the emergency state
function checkEmergencyTime() public view returns (uint256) {
return _emergencyTime;
}
// Check the duration of the emergency state
function checkEmergencyTimeLimit() public view returns (uint256) {
return _emergencyTimeLimit;
}
// Check the amount of personal pledged NNs
function checkEmergencyPerson(address user) public view returns (uint256) {
return _emergencyPerson[user];
}
// Check the number of NNs required for the emergency
function checkEmergencyNNAmount() public view returns (uint256) {
return _emergencyNNAmount;
}
// Verify voting contract data
function checkContractData(address contractAddress) public view returns (bool) {
return _contractData[contractAddress];
}
// Modify voting time
function changeLimitTime(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_limitTime = num;
}
// Modify the NestNode raising time
function changeNNLimitTime(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_NNLimitTime = num;
}
// Modify the voting proportion
function changeCirculationProportion(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_circulationProportion = num;
}
// Modify the minimum number of NNs to create a voting contract
function changeNNUsedCreate(uint256 num) public onlyOwner {
_NNUsedCreate = num;
}
// Modify the minimum number of NNs to raised to start a voting
function checkNNCreateLimit(uint256 num) public onlyOwner {
_NNCreateLimit = num;
}
// Modify the emergency state duration
function changeEmergencyTimeLimit(uint256 num) public onlyOwner {
require(num > 0);
_emergencyTimeLimit = num.mul(1 days);
}
// Modify the number of NNs required for emergency state
function changeEmergencyNNAmount(uint256 num) public onlyOwner {
require(num > 0);
_emergencyNNAmount = num;
}
// Check address
function checkAddress(string memory name) public view returns (address contractAddress) {
return _contractAddress[name];
}
// Add contract mapping address
function addContractAddress(string memory name, address contractAddress) public onlyOwner {
_contractAddress[name] = contractAddress;
}
// Add administrator address
function addSuperMan(address superMan) public onlyOwner {
_modifyAuthority[superMan] = true;
}
function addSuperManPrivate(address superMan) private {
_modifyAuthority[superMan] = true;
}
// Delete administrator address
function deleteSuperMan(address superMan) public onlyOwner {
_modifyAuthority[superMan] = false;
}
function deleteSuperManPrivate(address superMan) private {
_modifyAuthority[superMan] = false;
}
// Delete voting contract data
function deleteContractData(address contractAddress) public onlyOwner {
_contractData[contractAddress] = false;
}
// Check whether the administrator
function checkOwners(address man) public view returns (bool) {
return _modifyAuthority[man];
}
// Administrator only
modifier onlyOwner() {
require(checkOwners(msg.sender), "No authority");
_;
}
}
/**
* @title Voting contract
*/
contract Nest_3_VoteContract {
using SafeMath for uint256;
Nest_3_Implement _implementContract; // Executable contract
Nest_3_TokenSave _tokenSave; // Lock-up contract
Nest_3_VoteFactory _voteFactory; // Voting factory contract
Nest_3_TokenAbonus _tokenAbonus; // Bonus logic contract
ERC20 _nestToken; // NestToken
ERC20 _NNToken; // NestNode Token
address _miningSave; // Mining pool contract
address _implementAddress; // Executable contract address
address _destructionAddress; // Destruction contract address
uint256 _createTime; // Creation time
uint256 _endTime; // End time
uint256 _totalAmount; // Total votes
uint256 _circulation; // Passed votes
uint256 _destroyedNest; // Destroyed NEST
uint256 _NNLimitTime; // NestNode raising time
uint256 _NNCreateLimit; // Minimum number of NNs to create votes
uint256 _abonusTimes; // Period number of used snapshot in emergency state
uint256 _allNNAmount; // Total number of NNs
bool _effective = false; // Whether vote is effective
bool _nestVote = false; // Whether NEST vote can be performed
bool _isChange = false; // Whether NEST vote is executed
bool _stateOfEmergency; // Whether the contract is in emergency state
mapping(address => uint256) _personalAmount; // Number of personal votes
mapping(address => uint256) _personalNNAmount; // Number of NN personal votes
/**
* @dev Initialization method
* @param contractAddress Executable contract address
* @param stateOfEmergency Whether in emergency state
* @param NNAmount Amount of NNs
*/
constructor (address contractAddress, bool stateOfEmergency, uint256 NNAmount) public {
Nest_3_VoteFactory voteFactory = Nest_3_VoteFactory(address(msg.sender));
_voteFactory = voteFactory;
_nestToken = ERC20(voteFactory.checkAddress("nest"));
_NNToken = ERC20(voteFactory.checkAddress("nestNode"));
_implementContract = Nest_3_Implement(address(contractAddress));
_implementAddress = address(contractAddress);
_destructionAddress = address(voteFactory.checkAddress("nest.v3.destruction"));
_personalNNAmount[address(tx.origin)] = NNAmount;
_allNNAmount = NNAmount;
_createTime = now;
_endTime = _createTime.add(voteFactory.checkLimitTime());
_NNLimitTime = voteFactory.checkNNLimitTime();
_NNCreateLimit = voteFactory.checkNNCreateLimit();
_stateOfEmergency = stateOfEmergency;
if (stateOfEmergency) {
// If in emergency state, read the last two periods of bonus lock-up and total circulation data
_tokenAbonus = Nest_3_TokenAbonus(payable(voteFactory.checkAddress("nest.v3.tokenAbonus")));
_abonusTimes = _tokenAbonus.checkTimes().sub(2);
require(_abonusTimes > 0);
_circulation = _tokenAbonus.checkTokenAllValueHistory(address(_nestToken),_abonusTimes).mul(voteFactory.checkCirculationProportion()).div(100);
} else {
_miningSave = address(voteFactory.checkAddress("nest.v3.miningSave"));
_tokenSave = Nest_3_TokenSave(voteFactory.checkAddress("nest.v3.tokenSave"));
_circulation = (uint256(10000000000 ether).sub(_nestToken.balanceOf(address(_miningSave))).sub(_nestToken.balanceOf(address(_destructionAddress)))).mul(voteFactory.checkCirculationProportion()).div(100);
}
if (_allNNAmount >= _NNCreateLimit) {
_nestVote = true;
}
}
/**
* @dev NEST voting
*/
function nestVote() public onlyFactory {
require(now <= _endTime, "Voting time exceeded");
require(!_effective, "Vote in force");
require(_nestVote);
require(_personalAmount[address(tx.origin)] == 0, "Have voted");
uint256 amount;
if (_stateOfEmergency) {
// If in emergency state, read the last two periods of bonus lock-up and total circulation data
amount = _tokenAbonus.checkTokenSelfHistory(address(_nestToken),_abonusTimes, address(tx.origin));
} else {
amount = _tokenSave.checkAmount(address(tx.origin), address(_nestToken));
}
_personalAmount[address(tx.origin)] = amount;
_totalAmount = _totalAmount.add(amount);
ifEffective();
}
/**
* @dev NEST voting cancellation
*/
function nestVoteCancel() public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(now <= _endTime, "Voting time exceeded");
require(!_effective, "Vote in force");
require(_personalAmount[address(tx.origin)] > 0, "No vote");
_totalAmount = _totalAmount.sub(_personalAmount[address(tx.origin)]);
_personalAmount[address(tx.origin)] = 0;
}
/**
* @dev NestNode voting
* @param NNAmount Amount of NNs
*/
function nestNodeVote(uint256 NNAmount) public onlyFactory {
require(now <= _createTime.add(_NNLimitTime), "Voting time exceeded");
require(!_nestVote);
_personalNNAmount[address(tx.origin)] = _personalNNAmount[address(tx.origin)].add(NNAmount);
_allNNAmount = _allNNAmount.add(NNAmount);
if (_allNNAmount >= _NNCreateLimit) {
_nestVote = true;
}
}
/**
* @dev Withdrawing lock-up NNs
*/
function turnOutNestNode() public {
if (_nestVote) {
// Normal NEST voting
if (!_stateOfEmergency || !_effective) {
// Non-emergency state
require(now > _endTime, "Vote unenforceable");
}
} else {
// NN voting
require(now > _createTime.add(_NNLimitTime));
}
require(_personalNNAmount[address(tx.origin)] > 0);
// Reverting back the NNs
require(_NNToken.transfer(address(tx.origin), _personalNNAmount[address(tx.origin)]));
_personalNNAmount[address(tx.origin)] = 0;
// Destroying NEST Tokens
uint256 nestAmount = _nestToken.balanceOf(address(this));
_destroyedNest = _destroyedNest.add(nestAmount);
require(_nestToken.transfer(address(_destructionAddress), nestAmount));
}
/**
* @dev Execute the contract
*/
function startChange() public onlyFactory {
require(!_isChange);
_isChange = true;
if (_stateOfEmergency) {
require(_effective, "Vote unenforceable");
} else {
require(_effective && now > _endTime, "Vote unenforceable");
}
// Add the executable contract to the administrator list
_voteFactory.addSuperMan(address(_implementContract));
// Execute
_implementContract.doit();
// Delete the authorization
_voteFactory.deleteSuperMan(address(_implementContract));
}
/**
* @dev check whether the vote is effective
*/
function ifEffective() private {
if (_totalAmount >= _circulation) {
_effective = true;
}
}
/**
* @dev Check whether the vote is over
*/
function checkContractEffective() public view returns (bool) {
if (_effective || now > _endTime) {
return true;
}
return false;
}
// Check the executable implement contract address
function checkImplementAddress() public view returns (address) {
return _implementAddress;
}
// Check the voting start time
function checkCreateTime() public view returns (uint256) {
return _createTime;
}
// Check the voting end time
function checkEndTime() public view returns (uint256) {
return _endTime;
}
// Check the current total number of votes
function checkTotalAmount() public view returns (uint256) {
return _totalAmount;
}
// Check the number of votes to pass
function checkCirculation() public view returns (uint256) {
return _circulation;
}
// Check the number of personal votes
function checkPersonalAmount(address user) public view returns (uint256) {
return _personalAmount[user];
}
// Check the destroyed NEST
function checkDestroyedNest() public view returns (uint256) {
return _destroyedNest;
}
// Check whether the contract is effective
function checkEffective() public view returns (bool) {
return _effective;
}
// Check whether in emergency state
function checkStateOfEmergency() public view returns (bool) {
return _stateOfEmergency;
}
// Check NestNode raising time
function checkNNLimitTime() public view returns (uint256) {
return _NNLimitTime;
}
// Check the minimum number of NNs to create a vote
function checkNNCreateLimit() public view returns (uint256) {
return _NNCreateLimit;
}
// Check the period number of snapshot used in the emergency state
function checkAbonusTimes() public view returns (uint256) {
return _abonusTimes;
}
// Check number of personal votes
function checkPersonalNNAmount(address user) public view returns (uint256) {
return _personalNNAmount[address(user)];
}
// Check the total number of NNs
function checkAllNNAmount() public view returns (uint256) {
return _allNNAmount;
}
// Check whether NEST voting is available
function checkNestVote() public view returns (bool) {
return _nestVote;
}
// Check whether it has been excecuted
function checkIsChange() public view returns (bool) {
return _isChange;
}
// Vote Factory contract only
modifier onlyFactory() {
require(address(_voteFactory) == address(msg.sender), "No authority");
_;
}
}
/**
* @title Mining contract
* @dev Mining pool + mining logic
*/
contract Nest_3_MiningContract {
using address_make_payable for address;
using SafeMath for uint256;
uint256 _blockAttenuation = 2400000; // Block decay time interval
uint256[10] _attenuationAmount; // Mining decay amount
uint256 _afterMiningAmount = 40 ether; // Stable period mining amount
uint256 _firstBlockNum; // Starting mining block
uint256 _latestMining; // Latest offering block
Nest_3_VoteFactory _voteFactory; // Voting contract
ERC20 _nestContract; // NEST contract address
address _offerFactoryAddress; // Offering contract address
// Current block, current block mining amount
event OreDrawingLog(uint256 nowBlock, uint256 blockAmount);
/**
* @dev Initialization method
* @param voteFactory voting contract address
*/
constructor(address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
_offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain"));
_nestContract = ERC20(address(_voteFactory.checkAddress("nest")));
// Initiate mining parameters
_firstBlockNum = 6236588;
_latestMining = block.number;
uint256 blockAmount = 400 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(8).div(10);
}
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
_offerFactoryAddress = address(_voteFactory.checkAddress("nest.v3.offerMain"));
_nestContract = ERC20(address(_voteFactory.checkAddress("nest")));
}
/**
* @dev Offering mining
* @return Current block mining amount
*/
function oreDrawing() public returns (uint256) {
require(address(msg.sender) == _offerFactoryAddress, "No authority");
// Update mining amount list
uint256 miningAmount = changeBlockAmountList();
// Transfer NEST
if (_nestContract.balanceOf(address(this)) < miningAmount){
miningAmount = _nestContract.balanceOf(address(this));
}
if (miningAmount > 0) {
_nestContract.transfer(address(msg.sender), miningAmount);
emit OreDrawingLog(block.number,miningAmount);
}
return miningAmount;
}
/**
* @dev Update mining amount list
*/
function changeBlockAmountList() private returns (uint256) {
uint256 createBlock = _firstBlockNum;
uint256 recentlyUsedBlock = _latestMining;
uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock));
_latestMining = block.number;
return miningAmount;
}
/**
* @dev Transfer all NEST
* @param target Transfer target address
*/
function takeOutNest(address target) public onlyOwner {
_nestContract.transfer(address(target),_nestContract.balanceOf(address(this)));
}
// Check block decay time interval
function checkBlockAttenuation() public view returns(uint256) {
return _blockAttenuation;
}
// Check latest offering block
function checkLatestMining() public view returns(uint256) {
return _latestMining;
}
// Check mining amount decay
function checkAttenuationAmount(uint256 num) public view returns(uint256) {
return _attenuationAmount[num];
}
// Check NEST balance
function checkNestBalance() public view returns(uint256) {
return _nestContract.balanceOf(address(this));
}
// Modify block decay time interval
function changeBlockAttenuation(uint256 blockNum) public onlyOwner {
require(blockNum > 0);
_blockAttenuation = blockNum;
}
// Modify mining amount decay
function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner {
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(top).div(bottom);
}
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
/**
* @title Offering contract
* @dev Offering + take order + NEST allocation
*/
contract Nest_3_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
struct Nest_3_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_3_OfferPriceData [] _prices; // Array used to save offers
mapping(address => bool) _tokenAllow; // List of allowed mining token
Nest_3_VoteFactory _voteFactory; // Vote contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_3_MiningContract _miningContract; // Mining contract
Nest_NodeAssignment _NNcontract; // NestNode contract
ERC20 _nestToken; // NestToken
Nest_3_Abonus _abonus; // Bonus pool
address _coderAddress; // Developer address
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _coderAmount = 5; // Developer ratio
uint256 _NNAmount = 15; // NestNode ratio
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint32 _blockLimit = 25; // Block interval upper limit
mapping(uint256 => uint256) _offerBlockEth; // Block offer fee
mapping(uint256 => uint256) _offerBlockMining; // Block mining amount
// Log offering contract, token address, number of eth, number of erc20, number of continuous blocks, number of fees
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued, uint256 serviceCharge);
// Log transaction, transaction initiator, transaction token address, number of transaction token, token address, number of token, traded offering contract address, traded user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_miningContract = Nest_3_MiningContract(address(voteFactoryMap.checkAddress("nest.v3.miningSave")));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_NNcontract = Nest_NodeAssignment(address(voteFactoryMap.checkAddress("nodeAssignment")));
_coderAddress = voteFactoryMap.checkAddress("nest.v3.coder");
require(_nestToken.approve(address(_NNcontract), uint256(10000000000 ether)), "Authorization failed");
}
/**
* @dev Offering mining
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 token amount
* @param erc20Address Offering erc20 token address
*/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
require(_tokenAllow[erc20Address], "Token not allow");
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address, ethMining, isDeviate);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
// Mining
uint256 miningAmount = _miningContract.oreDrawing();
_abonus.switchToEth.value(ethMining)(address(_nestToken));
if (miningAmount > 0) {
uint256 coder = miningAmount.mul(_coderAmount).div(100);
uint256 NN = miningAmount.mul(_NNAmount).div(100);
uint256 other = miningAmount.sub(coder).sub(NN);
_offerBlockMining[block.number] = other;
_NNcontract.bookKeeping(NN);
if (coder > 0) {
_nestToken.safeTransfer(_coderAddress, coder);
}
}
_offerBlockEth[block.number] = _offerBlockEth[block.number].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
* @param mining Offering mining fee (0 for takers)
* @param isDeviate Whether the current price chain deviates
*/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, uint256 mining, bool isDeviate) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_3_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, 0, isDeviate);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
_abonus.switchToEth.value(serviceCharge)(address(_nestToken));
}
}
/**
* @dev Withdraw the assets, and settle the mining
* @param contractAddress The offer address to withdraw
*/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_3_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(offerPriceData.owner, payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
uint256 myMiningAmount = offerPriceData.serviceCharge.mul(_offerBlockMining[offerPriceData.blockNum]).div(_offerBlockEth[offerPriceData.blockNum]);
_nestToken.safeTransfer(offerPriceData.owner, myMiningAmount);
offerPriceData.serviceCharge = 0;
}
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
// View contract state
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Compare the order price
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint32) {
return _blockLimit;
}
// View offering mining fee ratio
function checkMiningETH() public view returns (uint256) {
return _miningETH;
}
// View whether the token is allowed to mine
function checkTokenAllow(address token) public view returns(bool) {
return _tokenAllow[token];
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View the development allocation ratio
function checkCoderAmount() public view returns(uint256) {
return _coderAmount;
}
// View the NestNode allocation ratio
function checkNNAmount() public view returns(uint256) {
return _NNAmount;
}
// View the least offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View the price deviation
function checkDeviate() public view returns(uint256){
return _deviate;
}
// View deviation from scale
function checkDeviationFromScale() public view returns(uint256) {
return _deviationFromScale;
}
// View block offer fee
function checkOfferBlockEth(uint256 blockNum) public view returns(uint256) {
return _offerBlockEth[blockNum];
}
// View taker order fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View block mining amount of user
function checkOfferBlockMining(uint256 blockNum) public view returns(uint256) {
return _offerBlockMining[blockNum];
}
// View offer mining amount
function checkOfferMining(uint256 blockNum, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _offerBlockMining[blockNum].mul(serviceCharge).div(_offerBlockEth[blockNum]);
}
}
// Change offering mining fee ratio
function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
// Modify taker fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify the upper limit of the block interval
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify whether the token allows mining
function changeTokenAllow(address token, bool allow) public onlyOwner {
_tokenAllow[token] = allow;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify the initial allocation ratio
function changeInitialRatio(uint256 coderNum, uint256 NNNum) public onlyOwner {
require(coderNum.add(NNNum) <= 100, "User allocation ratio error");
_coderAmount = coderNum;
_NNAmount = NNNum;
}
// Modify the minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0);
_leastEth = num;
}
// Modify the offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0);
_offerSpan = num;
}
// Modify the price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_3_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_3_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form and write it into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Vote administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
/**
* @title Price contract
* @dev Price check and call
*/
contract Nest_3_OfferPrice{
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
Nest_3_VoteFactory _voteFactory; // Voting contract
ERC20 _nestToken; // NestToken
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping
Nest_3_OfferMain _offerMain; // Offering main contract
Nest_3_Abonus _abonus; // Bonus pool
address _nTokeOfferMain; // NToken offering main contract
address _destructionAddress; // Destruction contract address
address _nTokenAuction; // NToken auction contract address
struct PriceInfo { // Block price
uint256 ethAmount; // ETH amount
uint256 erc20Amount; // Erc20 amount
uint256 frontBlock; // Last effective block
address offerOwner; // Offering address
}
struct TokenInfo { // Token offer information
mapping(uint256 => PriceInfo) priceInfoList; // Block price list, block number => block price
uint256 latestOffer; // Latest effective block
}
uint256 destructionAmount = 0 ether; // Amount of NEST to destroy to call prices
uint256 effectTime = 0 days; // Waiting time to start calling prices
mapping(address => TokenInfo) _tokenInfo; // Token offer information
mapping(address => bool) _blocklist; // Block list
mapping(address => uint256) _addressEffect; // Effective time of address to call prices
mapping(address => bool) _offerMainMapping; // Offering contract mapping
uint256 _priceCost = 0.01 ether; // Call price fee
// Real-time price token, ETH amount, erc20 amount
event NowTokenPrice(address a, uint256 b, uint256 c);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain")));
_nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain"));
_abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction"));
_offerMainMapping[address(_offerMain)] = true;
_offerMainMapping[address(_nTokeOfferMain)] = true;
}
/**
* @dev Modify voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerMain = Nest_3_OfferMain(address(voteFactoryMap.checkAddress("nest.v3.offerMain")));
_nTokeOfferMain = address(voteFactoryMap.checkAddress("nest.nToken.offerMain"));
_abonus = Nest_3_Abonus(address(voteFactoryMap.checkAddress("nest.v3.abonus")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nTokenAuction = address(voteFactoryMap.checkAddress("nest.nToken.tokenAuction"));
_offerMainMapping[address(_offerMain)] = true;
_offerMainMapping[address(_nTokeOfferMain)] = true;
}
/**
* @dev Initialize token price charge parameters
* @param tokenAddress Token address
*/
function addPriceCost(address tokenAddress) public {
}
/**
* @dev Add price
* @param ethAmount ETH amount
* @param tokenAmount Erc20 amount
* @param endBlock Effective price block
* @param tokenAddress Erc20 address
* @param offerOwner Offering address
*/
function addPrice(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) public onlyOfferMain{
// Add effective block price information
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock];
priceInfo.ethAmount = priceInfo.ethAmount.add(ethAmount);
priceInfo.erc20Amount = priceInfo.erc20Amount.add(tokenAmount);
if (endBlock != tokenInfo.latestOffer) {
// If different block offer
priceInfo.frontBlock = tokenInfo.latestOffer;
tokenInfo.latestOffer = endBlock;
}
}
/**
* @dev Price modification in taker orders
* @param ethAmount ETH amount
* @param tokenAmount Erc20 amount
* @param tokenAddress Token address
* @param endBlock Block of effective price
*/
function changePrice(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) public onlyOfferMain {
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
PriceInfo storage priceInfo = tokenInfo.priceInfoList[endBlock];
priceInfo.ethAmount = priceInfo.ethAmount.sub(ethAmount);
priceInfo.erc20Amount = priceInfo.erc20Amount.sub(tokenAmount);
}
/**
* @dev Update and check the latest price
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
* @return blockNum Price block
*/
function updateAndCheckPriceNow(address tokenAddress) public payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) {
require(checkUseNestPrice(address(msg.sender)));
mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList;
uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = priceInfoList[checkBlock].frontBlock;
}
require(checkBlock != 0);
PriceInfo memory priceInfo = priceInfoList[checkBlock];
address nToken = _tokenMapping.checkTokenMapping(tokenAddress);
if (nToken == address(0x0)) {
_abonus.switchToEth.value(_priceCost)(address(_nestToken));
} else {
_abonus.switchToEth.value(_priceCost)(address(nToken));
}
if (msg.value > _priceCost) {
repayEth(address(msg.sender), msg.value.sub(_priceCost));
}
emit NowTokenPrice(tokenAddress,priceInfo.ethAmount, priceInfo.erc20Amount);
return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock);
}
/**
* @dev Update and check the latest price-internal use
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
*/
function updateAndCheckPricePrivate(address tokenAddress) public view onlyOfferMain returns(uint256 ethAmount, uint256 erc20Amount) {
mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList;
uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = priceInfoList[checkBlock].frontBlock;
}
if (checkBlock == 0) {
return (0,0);
}
PriceInfo memory priceInfo = priceInfoList[checkBlock];
return (priceInfo.ethAmount,priceInfo.erc20Amount);
}
/**
* @dev Update and check the effective price list
* @param tokenAddress Token address
* @param num Number of prices to check
* @return uint256[] price list
*/
function updateAndCheckPriceList(address tokenAddress, uint256 num) public payable returns (uint256[] memory) {
require(checkUseNestPrice(address(msg.sender)));
mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList;
// Extract data
uint256 length = num.mul(3);
uint256 index = 0;
uint256[] memory data = new uint256[](length);
uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer;
while(index < length && checkBlock > 0){
if (checkBlock < block.number && priceInfoList[checkBlock].ethAmount != 0) {
// Add return data
data[index++] = priceInfoList[checkBlock].ethAmount;
data[index++] = priceInfoList[checkBlock].erc20Amount;
data[index++] = checkBlock;
}
checkBlock = priceInfoList[checkBlock].frontBlock;
}
require(length == data.length);
// Allocation
address nToken = _tokenMapping.checkTokenMapping(tokenAddress);
if (nToken == address(0x0)) {
_abonus.switchToEth.value(_priceCost)(address(_nestToken));
} else {
_abonus.switchToEth.value(_priceCost)(address(nToken));
}
if (msg.value > _priceCost) {
repayEth(address(msg.sender), msg.value.sub(_priceCost));
}
return data;
}
// Activate the price checking function
function activation() public {
_nestToken.safeTransferFrom(address(msg.sender), _destructionAddress, destructionAmount);
_addressEffect[address(msg.sender)] = now.add(effectTime);
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// Check block price - user account only
function checkPriceForBlock(address tokenAddress, uint256 blockNum) public view returns (uint256 ethAmount, uint256 erc20Amount) {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
TokenInfo storage tokenInfo = _tokenInfo[tokenAddress];
return (tokenInfo.priceInfoList[blockNum].ethAmount, tokenInfo.priceInfoList[blockNum].erc20Amount);
}
// Check real-time price - user account only
function checkPriceNow(address tokenAddress) public view returns (uint256 ethAmount, uint256 erc20Amount, uint256 blockNum) {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
mapping(uint256 => PriceInfo) storage priceInfoList = _tokenInfo[tokenAddress].priceInfoList;
uint256 checkBlock = _tokenInfo[tokenAddress].latestOffer;
while(checkBlock > 0 && (checkBlock >= block.number || priceInfoList[checkBlock].ethAmount == 0)) {
checkBlock = priceInfoList[checkBlock].frontBlock;
}
if (checkBlock == 0) {
return (0,0,0);
}
PriceInfo storage priceInfo = priceInfoList[checkBlock];
return (priceInfo.ethAmount,priceInfo.erc20Amount, checkBlock);
}
// Check whether the price-checking functions can be called
function checkUseNestPrice(address target) public view returns (bool) {
if (!_blocklist[target] && _addressEffect[target] < now && _addressEffect[target] != 0) {
return true;
} else {
return false;
}
}
// Check whether the address is in the blocklist
function checkBlocklist(address add) public view returns(bool) {
return _blocklist[add];
}
// Check the amount of NEST to destroy to call prices
function checkDestructionAmount() public view returns(uint256) {
return destructionAmount;
}
// Check the waiting time to start calling prices
function checkEffectTime() public view returns (uint256) {
return effectTime;
}
// Check call price fee
function checkPriceCost() public view returns (uint256) {
return _priceCost;
}
// Modify the blocklist
function changeBlocklist(address add, bool isBlock) public onlyOwner {
_blocklist[add] = isBlock;
}
// Amount of NEST to destroy to call price-checking functions
function changeDestructionAmount(uint256 amount) public onlyOwner {
destructionAmount = amount;
}
// Modify the waiting time to start calling prices
function changeEffectTime(uint256 num) public onlyOwner {
effectTime = num;
}
// Modify call price fee
function changePriceCost(uint256 num) public onlyOwner {
_priceCost = num;
}
// Offering contract only
modifier onlyOfferMain(){
require(_offerMainMapping[address(msg.sender)], "No authority");
_;
}
// Vote administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
/**
* @title NEST and NToken lock-up contract
* @dev NEST and NToken deposit and withdrawal
*/
contract Nest_3_TokenSave {
using SafeMath for uint256;
Nest_3_VoteFactory _voteFactory; // Voting contract
mapping(address => mapping(address => uint256)) _baseMapping; // Ledger token=>user=>amount
/**
* @dev initialization method
* @param voteFactory Voting contract address
*/
constructor(address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(voteFactory);
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
_voteFactory = Nest_3_VoteFactory(voteFactory);
}
/**
* @dev Withdrawing
* @param num Withdrawing amount
* @param token Lock-up token address
* @param target Transfer target
*/
function takeOut(uint256 num, address token, address target) public onlyContract {
require(num <= _baseMapping[token][address(target)], "Insufficient storage balance");
_baseMapping[token][address(target)] = _baseMapping[token][address(target)].sub(num);
ERC20(token).transfer(address(target), num);
}
/**
* @dev Depositing
* @param num Depositing amount
* @param token Lock-up token address
* @param target Depositing target
*/
function depositIn(uint256 num, address token, address target) public onlyContract {
require(ERC20(token).transferFrom(address(target),address(this),num), "Authorization transfer failed");
_baseMapping[token][address(target)] = _baseMapping[token][address(target)].add(num);
}
/**
* @dev Check the amount
* @param sender Check address
* @param token Lock-up token address
* @return uint256 Check address corresponding lock-up limit
*/
function checkAmount(address sender, address token) public view returns(uint256) {
return _baseMapping[token][address(sender)];
}
// Administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(address(msg.sender)), "No authority");
_;
}
// Only for bonus logic contract
modifier onlyContract(){
require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority");
_;
}
}
/**
* @title Dividend logic
* @dev Some operations about dividend,logic and asset separation
*/
contract Nest_3_TokenAbonus {
using address_make_payable for address;
using SafeMath for uint256;
ERC20 _nestContract;
Nest_3_TokenSave _tokenSave; // Lock-up contract
Nest_3_Abonus _abonusContract; // ETH bonus pool
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_Leveling _nestLeveling; // Leveling contract
address _destructionAddress; // Destroy contract address
uint256 _timeLimit = 168 hours; // Bonus period
uint256 _nextTime = 1596168000; // Next bonus time
uint256 _getAbonusTimeLimit = 60 hours; // During of triggering calculation of bonus
uint256 _times = 0; // Bonus ledger
uint256 _expectedIncrement = 3; // Expected bonus increment ratio
uint256 _expectedSpanForNest = 100000000 ether; // NEST expected bonus increment threshold
uint256 _expectedSpanForNToken = 1000000 ether; // NToken expected bonus increment threshold
uint256 _expectedMinimum = 100 ether; // Expected minimum bonus
uint256 _savingLevelOne = 10; // Saving threshold level 1
uint256 _savingLevelTwo = 20; // Saving threshold level 2
uint256 _savingLevelTwoSub = 100 ether; // Function parameters of savings threshold level 2
uint256 _savingLevelThree = 30; // Function parameters of savings threshold level 3
uint256 _savingLevelThreeSub = 600 ether; // Function parameters of savings threshold level 3
mapping(address => uint256) _abonusMapping; // Bonus pool snapshot - token address (NEST or NToken) => number of ETH in the bonus pool
mapping(address => uint256) _tokenAllValueMapping; // Number of tokens (circulation) - token address (NEST or NToken) ) => total circulation
mapping(address => mapping(uint256 => uint256)) _tokenAllValueHistory; // NEST or NToken circulation snapshot - token address (NEST or NToken) => number of periods => total circulation
mapping(address => mapping(uint256 => mapping(address => uint256))) _tokenSelfHistory; // Personal lockup - NEST or NToken snapshot token address (NEST or NToken) => period => user address => total circulation
mapping(address => mapping(uint256 => bool)) _snapshot; // Whether snapshot - token address (NEST or NToken) => number of periods => whether to take a snapshot
mapping(uint256 => mapping(address => mapping(address => bool))) _getMapping; // Receiving records - period => token address (NEST or NToken) => user address => whether received
// Log token address, amount
event GetTokenLog(address tokenAddress, uint256 tokenAmount);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_nestContract = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave")));
address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable();
_abonusContract = Nest_3_Abonus(addr);
address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable();
_nestLeveling = Nest_3_Leveling(levelingAddr);
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
}
/**
* @dev Modify voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_nestContract = ERC20(address(voteFactoryMap.checkAddress("nest")));
_tokenSave = Nest_3_TokenSave(address(voteFactoryMap.checkAddress("nest.v3.tokenSave")));
address payable addr = address(voteFactoryMap.checkAddress("nest.v3.abonus")).make_payable();
_abonusContract = Nest_3_Abonus(addr);
address payable levelingAddr = address(voteFactoryMap.checkAddress("nest.v3.leveling")).make_payable();
_nestLeveling = Nest_3_Leveling(levelingAddr);
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
}
/**
* @dev Deposit
* @param amount Deposited amount
* @param token Locked token address
*/
function depositIn(uint256 amount, address token) public {
uint256 nowTime = now;
uint256 nextTime = _nextTime;
uint256 timeLimit = _timeLimit;
if (nowTime < nextTime) {
// Bonus triggered
require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(_getAbonusTimeLimit)));
} else {
// Bonus not triggered
uint256 times = (nowTime.sub(_nextTime)).div(_timeLimit);
// Calculate the time when bonus should be started
uint256 startTime = _nextTime.add((times).mul(_timeLimit));
// Calculate the time when bonus should be stopped
uint256 endTime = startTime.add(_getAbonusTimeLimit);
require(!(nowTime >= startTime && nowTime <= endTime));
}
_tokenSave.depositIn(amount, token, address(msg.sender));
}
/**
* @dev Withdrawing
* @param amount Withdrawing amount
* @param token Token address
*/
function takeOut(uint256 amount, address token) public {
require(amount > 0, "Parameter needs to be greater than 0");
require(amount <= _tokenSave.checkAmount(address(msg.sender), token), "Insufficient storage balance");
if (token == address(_nestContract)) {
require(!_voteFactory.checkVoteNow(address(tx.origin)), "Voting");
}
_tokenSave.takeOut(amount, token, address(msg.sender));
}
/**
* @dev Receiving
* @param token Receiving token address
*/
function getAbonus(address token) public {
uint256 tokenAmount = _tokenSave.checkAmount(address(msg.sender), token);
require(tokenAmount > 0, "Insufficient storage balance");
reloadTime();
reloadToken(token);
uint256 nowTime = now;
require(nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit), "Not time to draw");
require(!_getMapping[_times.sub(1)][token][address(msg.sender)], "Have received");
_tokenSelfHistory[token][_times.sub(1)][address(msg.sender)] = tokenAmount;
require(_tokenAllValueMapping[token] > 0, "Total flux error");
uint256 selfNum = tokenAmount.mul(_abonusMapping[token]).div(_tokenAllValueMapping[token]);
require(selfNum > 0, "No limit available");
_getMapping[_times.sub(1)][token][address(msg.sender)] = true;
_abonusContract.getETH(selfNum, token,address(msg.sender));
emit GetTokenLog(token, selfNum);
}
/**
* @dev Update bonus time and stage ledger
*/
function reloadTime() private {
uint256 nowTime = now;
// The current time must exceed the bonus time
if (nowTime >= _nextTime) {
uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit);
uint256 startTime = _nextTime.add((time).mul(_timeLimit));
uint256 endTime = startTime.add(_getAbonusTimeLimit);
if (nowTime >= startTime && nowTime <= endTime) {
_nextTime = getNextTime();
_times = _times.add(1);
}
}
}
/**
* @dev Snapshot of the amount of tokens
* @param token Receiving token address
*/
function reloadToken(address token) private {
if (!_snapshot[token][_times.sub(1)]) {
levelingResult(token);
_abonusMapping[token] = _abonusContract.getETHNum(token);
_tokenAllValueMapping[token] = allValue(token);
_tokenAllValueHistory[token][_times.sub(1)] = allValue(token);
_snapshot[token][_times.sub(1)] = true;
}
}
/**
* @dev Leveling settlement
* @param token Receiving token address
*/
function levelingResult(address token) private {
uint256 steps;
if (token == address(_nestContract)) {
steps = allValue(token).div(_expectedSpanForNest);
} else {
steps = allValue(token).div(_expectedSpanForNToken);
}
uint256 minimumAbonus = _expectedMinimum;
for (uint256 i = 0; i < steps; i++) {
minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100));
}
uint256 thisAbonus = _abonusContract.getETHNum(token);
if (thisAbonus > minimumAbonus) {
uint256 levelAmount = 0;
if (thisAbonus > 5000 ether) {
levelAmount = thisAbonus.mul(_savingLevelThree).div(100).sub(_savingLevelThreeSub);
} else if (thisAbonus > 1000 ether) {
levelAmount = thisAbonus.mul(_savingLevelTwo).div(100).sub(_savingLevelTwoSub);
} else {
levelAmount = thisAbonus.mul(_savingLevelOne).div(100);
}
if (thisAbonus.sub(levelAmount) < minimumAbonus) {
_abonusContract.getETH(thisAbonus.sub(minimumAbonus), token, address(this));
_nestLeveling.switchToEth.value(thisAbonus.sub(minimumAbonus))(token);
} else {
_abonusContract.getETH(levelAmount, token, address(this));
_nestLeveling.switchToEth.value(levelAmount)(token);
}
} else {
uint256 ethValue = _nestLeveling.tranEth(minimumAbonus.sub(thisAbonus), token, address(this));
_abonusContract.switchToEth.value(ethValue)(token);
}
}
// Next bonus time, current bonus deadline, ETH number, NEST number, NEST participating in bonus, bonus to receive, approved amount, balance, whether bonus can be paid
function getInfo(address token) public view returns (uint256 nextTime, uint256 getAbonusTime, uint256 ethNum, uint256 tokenValue, uint256 myJoinToken, uint256 getEth, uint256 allowNum, uint256 leftNum, bool allowAbonus) {
uint256 nowTime = now;
if (nowTime >= _nextTime.sub(_timeLimit) && nowTime <= _nextTime.sub(_timeLimit).add(_getAbonusTimeLimit) && _times > 0 && _snapshot[token][_times.sub(1)]) {
// Bonus have been triggered, and during the time of this bonus, display snapshot data
allowAbonus = _getMapping[_times.sub(1)][token][address(msg.sender)];
ethNum = _abonusMapping[token];
tokenValue = _tokenAllValueMapping[token];
} else {
// Display real-time data
ethNum = _abonusContract.getETHNum(token);
tokenValue = allValue(token);
allowAbonus = _getMapping[_times][token][address(msg.sender)];
}
myJoinToken = _tokenSave.checkAmount(address(msg.sender), token);
if (allowAbonus == true) {
getEth = 0;
} else {
getEth = myJoinToken.mul(ethNum).div(tokenValue);
}
nextTime = getNextTime();
getAbonusTime = nextTime.sub(_timeLimit).add(_getAbonusTimeLimit);
allowNum = ERC20(token).allowance(address(msg.sender), address(_tokenSave));
leftNum = ERC20(token).balanceOf(address(msg.sender));
}
/**
* @dev View next bonus time
* @return Next bonus time
*/
function getNextTime() public view returns (uint256) {
uint256 nowTime = now;
if (_nextTime > nowTime) {
return _nextTime;
} else {
uint256 time = (nowTime.sub(_nextTime)).div(_timeLimit);
return _nextTime.add(_timeLimit.mul(time.add(1)));
}
}
/**
* @dev View total circulation
* @return Total circulation
*/
function allValue(address token) public view returns (uint256) {
if (token == address(_nestContract)) {
uint256 all = 10000000000 ether;
uint256 leftNum = all.sub(_nestContract.balanceOf(address(_voteFactory.checkAddress("nest.v3.miningSave")))).sub(_nestContract.balanceOf(address(_destructionAddress)));
return leftNum;
} else {
return ERC20(token).totalSupply();
}
}
/**
* @dev View bonus period
* @return Bonus period
*/
function checkTimeLimit() public view returns (uint256) {
return _timeLimit;
}
/**
* @dev View duration of triggering calculation of bonus
* @return Bonus period
*/
function checkGetAbonusTimeLimit() public view returns (uint256) {
return _getAbonusTimeLimit;
}
/**
* @dev View current lowest expected bonus
* @return Current lowest expected bonus
*/
function checkMinimumAbonus(address token) public view returns (uint256) {
uint256 miningAmount;
if (token == address(_nestContract)) {
miningAmount = allValue(token).div(_expectedSpanForNest);
} else {
miningAmount = allValue(token).div(_expectedSpanForNToken);
}
uint256 minimumAbonus = _expectedMinimum;
for (uint256 i = 0; i < miningAmount; i++) {
minimumAbonus = minimumAbonus.add(minimumAbonus.mul(_expectedIncrement).div(100));
}
return minimumAbonus;
}
/**
* @dev Check whether the bonus token is snapshoted
* @param token Token address
* @return Whether snapshoted
*/
function checkSnapshot(address token) public view returns (bool) {
return _snapshot[token][_times.sub(1)];
}
/**
* @dev Check the expected bonus incremental ratio
* @return Expected bonus increment ratio
*/
function checkeExpectedIncrement() public view returns (uint256) {
return _expectedIncrement;
}
/**
* @dev View expected minimum bonus
* @return Expected minimum bonus
*/
function checkExpectedMinimum() public view returns (uint256) {
return _expectedMinimum;
}
/**
* @dev View savings threshold
* @return Save threshold
*/
function checkSavingLevelOne() public view returns (uint256) {
return _savingLevelOne;
}
function checkSavingLevelTwo() public view returns (uint256) {
return _savingLevelTwo;
}
function checkSavingLevelThree() public view returns (uint256) {
return _savingLevelThree;
}
/**
* @dev View NEST liquidity snapshot
* @param token Locked token address
* @param times Bonus snapshot period
*/
function checkTokenAllValueHistory(address token, uint256 times) public view returns (uint256) {
return _tokenAllValueHistory[token][times];
}
/**
* @dev View personal lock-up NEST snapshot
* @param times Bonus snapshot period
* @param user User address
* @return The number of personal locked NEST snapshots
*/
function checkTokenSelfHistory(address token, uint256 times, address user) public view returns (uint256) {
return _tokenSelfHistory[token][times][user];
}
// View the period number of bonus
function checkTimes() public view returns (uint256) {
return _times;
}
// NEST expected bonus increment threshold
function checkExpectedSpanForNest() public view returns (uint256) {
return _expectedSpanForNest;
}
// NToken expected bonus increment threshold
function checkExpectedSpanForNToken() public view returns (uint256) {
return _expectedSpanForNToken;
}
// View the function parameters of savings threshold level 3
function checkSavingLevelTwoSub() public view returns (uint256) {
return _savingLevelTwoSub;
}
// View the function parameters of savings threshold level 3
function checkSavingLevelThreeSub() public view returns (uint256) {
return _savingLevelThreeSub;
}
/**
* @dev Update bonus period
* @param hour Bonus period (hours)
*/
function changeTimeLimit(uint256 hour) public onlyOwner {
require(hour > 0, "Parameter needs to be greater than 0");
_timeLimit = hour.mul(1 hours);
}
/**
* @dev Update collection period
* @param hour Collection period (hours)
*/
function changeGetAbonusTimeLimit(uint256 hour) public onlyOwner {
require(hour > 0, "Parameter needs to be greater than 0");
_getAbonusTimeLimit = hour;
}
/**
* @dev Update expected bonus increment ratio
* @param num Expected bonus increment ratio
*/
function changeExpectedIncrement(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_expectedIncrement = num;
}
/**
* @dev Update expected minimum bonus
* @param num Expected minimum bonus
*/
function changeExpectedMinimum(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_expectedMinimum = num;
}
/**
* @dev Update saving threshold
* @param threshold Saving threshold
*/
function changeSavingLevelOne(uint256 threshold) public onlyOwner {
_savingLevelOne = threshold;
}
function changeSavingLevelTwo(uint256 threshold) public onlyOwner {
_savingLevelTwo = threshold;
}
function changeSavingLevelThree(uint256 threshold) public onlyOwner {
_savingLevelThree = threshold;
}
/**
* @dev Update the function parameters of savings threshold level 2
*/
function changeSavingLevelTwoSub(uint256 num) public onlyOwner {
_savingLevelTwoSub = num;
}
/**
* @dev Update the function parameters of savings threshold level 3
*/
function changeSavingLevelThreeSub(uint256 num) public onlyOwner {
_savingLevelThreeSub = num;
}
/**
* @dev Update NEST expected bonus incremental threshold
* @param num Threshold
*/
function changeExpectedSpanForNest(uint256 num) public onlyOwner {
_expectedSpanForNest = num;
}
/**
* @dev Update NToken expected bonus incremental threshold
* @param num Threshold
*/
function changeExpectedSpanForNToken(uint256 num) public onlyOwner {
_expectedSpanForNToken = num;
}
receive() external payable {
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(address(msg.sender)), "No authority");
_;
}
}
/**
* @title ETH bonus pool
* @dev ETH collection and inquiry
*/
contract Nest_3_Abonus {
using address_make_payable for address;
using SafeMath for uint256;
Nest_3_VoteFactory _voteFactory; // Voting contract
address _nestAddress; // NEST contract address
mapping (address => uint256) ethMapping; // ETH bonus ledger of corresponding tokens
uint256 _mostDistribution = 40; // The highest allocation ratio of NEST bonus pool
uint256 _leastDistribution = 20; // The lowest allocation ratio of NEST bonus pool
uint256 _distributionTime = 1200000; // The decay time interval of NEST bonus pool allocation ratio
uint256 _distributionSpan = 5; // The decay degree of NEST bonus pool allocation ratio
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor(address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(voteFactory);
_nestAddress = address(_voteFactory.checkAddress("nest"));
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner{
_voteFactory = Nest_3_VoteFactory(voteFactory);
_nestAddress = address(_voteFactory.checkAddress("nest"));
}
/**
* @dev Transfer in bonus
* @param token Corresponding to lock-up Token
*/
function switchToEth(address token) public payable {
ethMapping[token] = ethMapping[token].add(msg.value);
}
/**
* @dev Transferin bonus - NToken offering fee
* @param token Corresponding to lock-up NToken
*/
function switchToEthForNTokenOffer(address token) public payable {
Nest_NToken nToken = Nest_NToken(token);
(uint256 createBlock,) = nToken.checkBlockInfo();
uint256 subBlock = block.number.sub(createBlock);
uint256 times = subBlock.div(_distributionTime);
uint256 distributionValue = times.mul(_distributionSpan);
uint256 distribution = _mostDistribution;
if (_leastDistribution.add(distributionValue) > _mostDistribution) {
distribution = _leastDistribution;
} else {
distribution = _mostDistribution.sub(distributionValue);
}
uint256 nestEth = msg.value.mul(distribution).div(100);
ethMapping[_nestAddress] = ethMapping[_nestAddress].add(nestEth);
ethMapping[token] = ethMapping[token].add(msg.value.sub(nestEth));
}
/**
* @dev Receive ETH
* @param num Receive amount
* @param token Correspond to locked Token
* @param target Transfer target
*/
function getETH(uint256 num, address token, address target) public onlyContract {
require(num <= ethMapping[token], "Insufficient storage balance");
ethMapping[token] = ethMapping[token].sub(num);
address payable addr = target.make_payable();
addr.transfer(num);
}
/**
* @dev Get bonus pool balance
* @param token Corresponded locked Token
* @return uint256 Bonus pool balance
*/
function getETHNum(address token) public view returns (uint256) {
return ethMapping[token];
}
// View NEST address
function checkNestAddress() public view returns(address) {
return _nestAddress;
}
// View the highest NEST bonus pool allocation ratio
function checkMostDistribution() public view returns(uint256) {
return _mostDistribution;
}
// View the lowest NEST bonus pool allocation ratio
function checkLeastDistribution() public view returns(uint256) {
return _leastDistribution;
}
// View the decay time interval of NEST bonus pool allocation ratio
function checkDistributionTime() public view returns(uint256) {
return _distributionTime;
}
// View the decay degree of NEST bonus pool allocation ratio
function checkDistributionSpan() public view returns(uint256) {
return _distributionSpan;
}
// Modify the highest NEST bonus pool allocation ratio
function changeMostDistribution(uint256 num) public onlyOwner {
_mostDistribution = num;
}
// Modify the lowest NEST bonus pool allocation ratio
function changeLeastDistribution(uint256 num) public onlyOwner {
_leastDistribution = num;
}
// Modify the decay time interval of NEST bonus pool allocation ratio
function changeDistributionTime(uint256 num) public onlyOwner {
_distributionTime = num;
}
// Modify the decay degree of NEST bonus pool allocation ratio
function changeDistributionSpan(uint256 num) public onlyOwner {
_distributionSpan = num;
}
// Withdraw ETH
function turnOutAllEth(uint256 amount, address target) public onlyOwner {
address payable addr = target.make_payable();
addr.transfer(amount);
}
// Only bonus logic contract
modifier onlyContract(){
require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority");
_;
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(address(msg.sender)), "No authority");
_;
}
}
/**
* @title Leveling contract
* @dev ETH transfer in and transfer out
*/
contract Nest_3_Leveling {
using address_make_payable for address;
using SafeMath for uint256;
Nest_3_VoteFactory _voteFactory; // Vote contract
mapping (address => uint256) ethMapping; // Corresponded ETH leveling ledger of token
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(voteFactory);
}
/**
* @dev Modifying voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
_voteFactory = Nest_3_VoteFactory(voteFactory);
}
/**
* @dev Transfer out leveling
* @param amount Transfer-out amount
* @param token Corresponding lock-up token
* @param target Transfer-out target
*/
function tranEth(uint256 amount, address token, address target) public returns (uint256) {
require(address(msg.sender) == address(_voteFactory.checkAddress("nest.v3.tokenAbonus")), "No authority");
uint256 tranAmount = amount;
if (tranAmount > ethMapping[token]) {
tranAmount = ethMapping[token];
}
ethMapping[token] = ethMapping[token].sub(tranAmount);
address payable addr = target.make_payable();
addr.transfer(tranAmount);
return tranAmount;
}
/**
* @dev Transfer in leveling
* @param token Corresponded locked token
*/
function switchToEth(address token) public payable {
ethMapping[token] = ethMapping[token].add(msg.value);
}
// Check the leveled amount corresponding to the token
function checkEthMapping(address token) public view returns (uint256) {
return ethMapping[token];
}
// Withdraw ETH
function turnOutAllEth(uint256 amount, address target) public onlyOwner {
address payable addr = target.make_payable();
addr.transfer(amount);
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(address(msg.sender)), "No authority");
_;
}
}
/**
* @title Offering contract
* @dev Offering logic and mining logic
*/
contract Nest_NToken_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
// Offering data structure
struct Nest_NToken_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_NToken_OfferPriceData [] _prices; // Array used to save offers
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // nestToken
Nest_3_Abonus _abonus; // Bonus pool
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint256 _ownerMining = 5; // Creator ratio
uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount
uint32 _blockLimit = 25; // Block interval upper limit
uint256 _blockAttenuation = 2400000; // Block decay interval
mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee
mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount
uint256[10] _attenuationAmount; // Mining decay list
// Log token contract address
event OfferTokenContractAddress(address contractAddress);
// Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee
event OfferContractAddress(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining);
// Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address
event OfferTran(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner);
// Log current block, current block mined amount, token address
event OreDrawingLog(uint256 nowBlock, uint256 blockAmount, address tokenAddress);
// Log offering block, token address, token offered times
event MiningLog(uint256 blockNum, address tokenAddress, uint256 offerTimes);
/**
* Initialization method
* @param voteFactory Voting contract address
**/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
uint256 blockAmount = 4 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(8).div(10);
}
}
/**
* Reset voting contract method
* @param voteFactory Voting contract address
**/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.checkAddress("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.checkAddress("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
}
/**
* Offering method
* @param ethAmount ETH amount
* @param erc20Amount Erc20 token amount
* @param erc20Address Erc20 token address
**/
function offer(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
address nTokenAddress = _tokenMapping.checkTokenMapping(erc20Address);
require(nTokenAddress != address(0x0));
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = comparativePrice(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.mul(_miningETH).div(1000);
} else {
ethMining = ethAmount.mul(_miningETH).div(1000);
}
require(msg.value >= ethAmount.add(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.sub(ethAmount.add(ethMining));
if (subValue > 0) {
repayEth(address(msg.sender), subValue);
}
// Create an offer
createOffer(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).safeTransferFrom(address(msg.sender), address(this), erc20Amount);
_abonus.switchToEthForNTokenOffer.value(ethMining)(nTokenAddress);
// Mining
if (_blockOfferAmount[block.number][erc20Address] == 0) {
uint256 miningAmount = oreDrawing(nTokenAddress);
Nest_NToken nToken = Nest_NToken(nTokenAddress);
nToken.transfer(nToken.checkBidder(), miningAmount.mul(_ownerMining).div(100));
_blockMining[block.number][erc20Address] = miningAmount.sub(miningAmount.mul(_ownerMining).div(100));
}
_blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].add(ethMining);
}
/**
* @dev Create offer
* @param ethAmount Offering ETH amount
* @param erc20Amount Offering erc20 amount
* @param erc20Address Offering erc20 address
**/
function createOffer(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private {
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.div(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OfferContractAddress(toAddress(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_NToken_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.addPrice(ethAmount, erc20Amount, block.number.add(_blockLimit), erc20Address, address(msg.sender));
}
// Convert offer address into index in offer array
function toIndex(address contractAddress) public pure returns(uint256) {
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function toAddress(uint256 index) public pure returns(address) {
return address(index);
}
/**
* Withdraw offer assets
* @param contractAddress Offer address
**/
function turnOut(address contractAddress) public {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData storage offerPriceData = _prices[index];
require(checkContractState(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
repayEth(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).safeTransfer(address(offerPriceData.owner), payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
mining(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner);
offerPriceData.serviceCharge = 0;
}
}
/**
* @dev Taker order - pay ETH and buy erc20
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendEthBuyErc(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.add(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.add(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.sub(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tokenAmount.sub(tranTokenAmount));
} else {
ERC20(tranTokenAddress).safeTransfer(address(msg.sender), tranTokenAmount.sub(tokenAmount));
}
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* @dev Taker order - pay erc20 and buy ETH
* @param ethAmount The amount of ETH of this offer
* @param tokenAmount The amount of erc20 of this offer
* @param contractAddress The target offer address
* @param tranEthAmount The amount of ETH of taker order
* @param tranTokenAmount The amount of erc20 of taker order
* @param tranTokenAddress The erc20 address of taker order
*/
function sendErcBuyEth(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable {
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.mul(_tranEth).div(1000);
require(msg.value == ethAmount.sub(tranEthAmount).add(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = toIndex(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = comparativePrice(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.mul(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.mul(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(checkContractState(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.sub(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.add(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.sub(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.sub(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
createOffer(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).safeTransferFrom(address(msg.sender), address(this), tranTokenAmount.add(tokenAmount));
// Modify price
_offerPrice.changePrice(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.add(_blockLimit));
emit OfferTran(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.checkTokenMapping(tranTokenAddress);
_abonus.switchToEth.value(serviceCharge)(nTokenAddress);
}
}
/**
* Offering mining
* @param ntoken NToken address
**/
function oreDrawing(address ntoken) private returns(uint256) {
Nest_NToken miningToken = Nest_NToken(ntoken);
(uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.checkBlockInfo();
uint256 attenuationPointNow = block.number.sub(createBlock).div(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.mul(block.number.sub(recentlyUsedBlock));
miningToken.increaseTotal(miningAmount);
emit OreDrawingLog(block.number, miningAmount, ntoken);
return miningAmount;
}
/**
* Retrieve mining
* @param token Token address
**/
function mining(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) {
// Block mining amount*offer fee/block offer fee
uint256 miningAmount = _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
// Transfer NToken
Nest_NToken nToken = Nest_NToken(address(_tokenMapping.checkTokenMapping(token)));
require(nToken.transfer(address(owner), miningAmount), "Transfer failure");
emit MiningLog(blockNum, token,_blockOfferAmount[blockNum][token]);
return miningAmount;
}
// Compare order prices
function comparativePrice(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) {
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.updateAndCheckPricePrivate(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).add(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.mul(frontTokenValue).mul(uint256(100).sub(_deviate)).div(frontEthValue.mul(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Check contract status
function checkContractState(uint256 createBlock) public view returns (uint256) {
if (block.number.sub(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Transfer ETH
function repayEth(address accountAddress, uint256 asset) private {
address payable addr = accountAddress.make_payable();
addr.transfer(asset);
}
// View the upper limit of the block interval
function checkBlockLimit() public view returns(uint256) {
return _blockLimit;
}
// View taker fee ratio
function checkTranEth() public view returns (uint256) {
return _tranEth;
}
// View additional transaction multiple
function checkTranAddition() public view returns(uint256) {
return _tranAddition;
}
// View minimum offering ETH
function checkleastEth() public view returns(uint256) {
return _leastEth;
}
// View offering ETH span
function checkOfferSpan() public view returns(uint256) {
return _offerSpan;
}
// View block offering amount
function checkBlockOfferAmount(uint256 blockNum, address token) public view returns (uint256) {
return _blockOfferAmount[blockNum][token];
}
// View offering block mining amount
function checkBlockMining(uint256 blockNum, address token) public view returns (uint256) {
return _blockMining[blockNum][token];
}
// View offering mining amount
function checkOfferMining(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) {
if (serviceCharge == 0) {
return 0;
} else {
return _blockMining[blockNum][token].mul(serviceCharge).div(_blockOfferAmount[blockNum][token]);
}
}
// View the owner allocation ratio
function checkOwnerMining() public view returns(uint256) {
return _ownerMining;
}
// View the mining decay
function checkAttenuationAmount(uint256 num) public view returns(uint256) {
return _attenuationAmount[num];
}
// Modify taker order fee ratio
function changeTranEth(uint256 num) public onlyOwner {
_tranEth = num;
}
// Modify block interval upper limit
function changeBlockLimit(uint32 num) public onlyOwner {
_blockLimit = num;
}
// Modify additional transaction multiple
function changeTranAddition(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify minimum offering ETH
function changeLeastEth(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
// Modify offering ETH span
function changeOfferSpan(uint256 num) public onlyOwner {
require(num > 0, "Parameter needs to be greater than 0");
_offerSpan = num;
}
// Modify price deviation
function changekDeviate(uint256 num) public onlyOwner {
_deviate = num;
}
// Modify the deviation from scale
function changeDeviationFromScale(uint256 num) public onlyOwner {
_deviationFromScale = num;
}
// Modify the owner allocation ratio
function changeOwnerMining(uint256 num) public onlyOwner {
_ownerMining = num;
}
// Modify the mining decay
function changeAttenuationAmount(uint256 firstAmount, uint256 top, uint256 bottom) public onlyOwner {
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.mul(top).div(bottom);
}
}
// Vote administrators only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
/**
* Get the number of offers stored in the offer array
* @return The number of offers stored in the offer array
**/
function getPriceCount() view public returns (uint256) {
return _prices.length;
}
/**
* Get offer information according to the index
* @param priceIndex Offer index
* @return Offer information
**/
function getPrice(uint256 priceIndex) view public returns (string memory) {
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = writeOfferPriceData(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Search the contract address list of the target account (reverse order)
* @param start Search forward from the index corresponding to the given contract address (not including the record corresponding to start address)
* @param count Maximum number of records to return
* @param maxFindCount The max index to search
* @param owner Target account address
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function find(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = toIndex(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = writeOfferPriceData(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
/**
* Get the list of offers by page
* @param offset Skip the first offset records
* @param count Maximum number of records to return
* @param order Sort rules. 0 means reverse order, non-zero means positive order
* @return Separate the offer records with symbols. use , to divide fields:
* uuid,owner,tokenAddress,ethAmount,tokenAmount,dealEthAmount,dealTokenAmount,blockNum,serviceCharge
**/
function list(uint256 offset, uint256 count, uint256 order) view public returns (string memory) {
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = writeOfferPriceData(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function writeOfferPriceData(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) {
index = writeAddress(toAddress(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = writeAddress(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = writeUInt(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form, write the string into the buffer, and return the buffer index
function writeUInt(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) {
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function writeAddress(address addr, bytes memory buf, uint256 index) pure private returns (uint256) {
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
}
/**
* @title Auction NToken contract
* @dev Auction for listing and generating NToken
*/
contract Nest_NToken_TokenAuction {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // NestToken
Nest_3_OfferPrice _offerPrice; // Price contract
address _destructionAddress; // Destruction contract address
uint256 _duration = 5 days; // Auction duration
uint256 _minimumNest = 100000 ether; // Minimum auction amount
uint256 _tokenNum = 1; // Auction token number
uint256 _incentiveRatio = 50; // Incentive ratio
uint256 _minimumInterval = 10000 ether; // Minimum auction interval
mapping(address => AuctionInfo) _auctionList; // Auction list
mapping(address => bool) _tokenBlackList; // Auction blacklist
struct AuctionInfo {
uint256 endTime; // End time
uint256 auctionValue; // Auction price
address latestAddress; // Highest auctioneer
uint256 latestAmount; // Lastest auction amount
}
address[] _allAuction; // Auction list array
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.checkAddress("nest.nToken.tokenMapping")));
_nestToken = ERC20(address(voteFactoryMap.checkAddress("nest")));
_destructionAddress = address(voteFactoryMap.checkAddress("nest.v3.destruction"));
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
}
/**
* @dev Initiating auction
* @param token Auction token address
* @param auctionAmount Initial auction amount
*/
function startAnAuction(address token, uint256 auctionAmount) public {
require(_tokenMapping.checkTokenMapping(token) == address(0x0), "Token already exists");
require(_auctionList[token].endTime == 0, "Token is on sale");
require(auctionAmount >= _minimumNest, "AuctionAmount less than the minimum auction amount");
require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed");
require(!_tokenBlackList[token]);
// Verification
ERC20 tokenERC20 = ERC20(token);
tokenERC20.safeTransferFrom(address(msg.sender), address(this), 1);
require(tokenERC20.balanceOf(address(this)) >= 1);
tokenERC20.safeTransfer(address(msg.sender), 1);
AuctionInfo memory thisAuction = AuctionInfo(now.add(_duration), auctionAmount, address(msg.sender), auctionAmount);
_auctionList[token] = thisAuction;
_allAuction.push(token);
}
/**
* @dev Auction
* @param token Auction token address
* @param auctionAmount Auction amount
*/
function continueAuction(address token, uint256 auctionAmount) public {
require(now <= _auctionList[token].endTime && _auctionList[token].endTime != 0, "Auction closed");
require(auctionAmount > _auctionList[token].auctionValue, "Insufficient auction amount");
uint256 subAuctionAmount = auctionAmount.sub(_auctionList[token].auctionValue);
require(subAuctionAmount >= _minimumInterval);
uint256 excitation = subAuctionAmount.mul(_incentiveRatio).div(100);
require(_nestToken.transferFrom(address(msg.sender), address(this), auctionAmount), "Authorization failed");
require(_nestToken.transfer(_auctionList[token].latestAddress, _auctionList[token].auctionValue.add(excitation)), "Transfer failure");
// Update auction information
_auctionList[token].auctionValue = auctionAmount;
_auctionList[token].latestAddress = address(msg.sender);
_auctionList[token].latestAmount = _auctionList[token].latestAmount.add(subAuctionAmount.sub(excitation));
}
/**
* @dev Listing
* @param token Auction token address
*/
function auctionSuccess(address token) public {
Nest_3_TokenAbonus nestAbonus = Nest_3_TokenAbonus(payable(_voteFactory.checkAddress("nest.v3.tokenAbonus")));
uint256 nowTime = now;
uint256 nextTime = nestAbonus.getNextTime();
uint256 timeLimit = nestAbonus.checkTimeLimit();
uint256 getAbonusTimeLimit = nestAbonus.checkGetAbonusTimeLimit();
require(!(nowTime >= nextTime.sub(timeLimit) && nowTime <= nextTime.sub(timeLimit).add(getAbonusTimeLimit)), "Not time to auctionSuccess");
require(nowTime > _auctionList[token].endTime && _auctionList[token].endTime != 0, "Token is on sale");
// Initialize NToken
Nest_NToken nToken = new Nest_NToken(strConcat("NToken", getAddressStr(_tokenNum)), strConcat("N", getAddressStr(_tokenNum)), address(_voteFactory), address(_auctionList[token].latestAddress));
// Auction NEST destruction
require(_nestToken.transfer(_destructionAddress, _auctionList[token].latestAmount), "Transfer failure");
// Add NToken mapping
_tokenMapping.addTokenMapping(token, address(nToken));
// Initialize charging parameters
_offerPrice.addPriceCost(token);
_tokenNum = _tokenNum.add(1);
}
function strConcat(string memory _a, string memory _b) public pure returns (string memory){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ret = new string(_ba.length + _bb.length);
bytes memory bret = bytes(ret);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
bret[k++] = _ba[i];
}
for (uint i = 0; i < _bb.length; i++) {
bret[k++] = _bb[i];
}
return string(ret);
}
// Convert to 4-digit string
function getAddressStr(uint256 iv) public pure returns (string memory) {
bytes memory buf = new bytes(64);
uint256 index = 0;
do {
buf[index++] = byte(uint8(iv % 10 + 48));
iv /= 10;
} while (iv > 0 || index < 4);
bytes memory str = new bytes(index);
for(uint256 i = 0; i < index; ++i) {
str[i] = buf[index - i - 1];
}
return string(str);
}
// Check auction duration
function checkDuration() public view returns(uint256) {
return _duration;
}
// Check minimum auction amount
function checkMinimumNest() public view returns(uint256) {
return _minimumNest;
}
// Check initiated number of auction tokens
function checkAllAuctionLength() public view returns(uint256) {
return _allAuction.length;
}
// View auctioned token addresses
function checkAuctionTokenAddress(uint256 num) public view returns(address) {
return _allAuction[num];
}
// View auction blacklist
function checkTokenBlackList(address token) public view returns(bool) {
return _tokenBlackList[token];
}
// View auction token information
function checkAuctionInfo(address token) public view returns(uint256 endTime, uint256 auctionValue, address latestAddress) {
AuctionInfo memory info = _auctionList[token];
return (info.endTime, info.auctionValue, info.latestAddress);
}
// View token number
function checkTokenNum() public view returns (uint256) {
return _tokenNum;
}
// Modify auction duration
function changeDuration(uint256 num) public onlyOwner {
_duration = num.mul(1 days);
}
// Modify minimum auction amount
function changeMinimumNest(uint256 num) public onlyOwner {
_minimumNest = num;
}
// Modify auction blacklist
function changeTokenBlackList(address token, bool isBlack) public onlyOwner {
_tokenBlackList[token] = isBlack;
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
contract Nest_NToken is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances; // Balance ledger
mapping (address => mapping (address => uint256)) private _allowed; // Approval ledger
uint256 private _totalSupply = 0 ether; // Total supply
string public name; // Token name
string public symbol; // Token symbol
uint8 public decimals = 18; // Precision
uint256 public _createBlock; // Create block number
uint256 public _recentlyUsedBlock; // Recently used block number
Nest_3_VoteFactory _voteFactory; // Voting factory contract
address _bidder; // Owner
/**
* @dev Initialization method
* @param _name Token name
* @param _symbol Token symbol
* @param voteFactory Voting factory contract address
* @param bidder Successful bidder address
*/
constructor (string memory _name, string memory _symbol, address voteFactory, address bidder) public {
name = _name;
symbol = _symbol;
_createBlock = block.number;
_recentlyUsedBlock = block.number;
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
_bidder = bidder;
}
/**
* @dev Reset voting contract method
* @param voteFactory Voting contract address
*/
function changeMapping (address voteFactory) public onlyOwner {
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
}
/**
* @dev Additional issuance
* @param value Additional issuance amount
*/
function increaseTotal(uint256 value) public {
address offerMain = address(_voteFactory.checkAddress("nest.nToken.offerMain"));
require(address(msg.sender) == offerMain, "No authority");
_balances[offerMain] = _balances[offerMain].add(value);
_totalSupply = _totalSupply.add(value);
_recentlyUsedBlock = block.number;
}
/**
* @dev Check the total amount of tokens
* @return Total supply
*/
function totalSupply() override public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Check address balance
* @param owner Address to be checked
* @return Return the balance of the corresponding address
*/
function balanceOf(address owner) override public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Check block information
* @return createBlock Initial block number
* @return recentlyUsedBlock Recently mined and issued block
*/
function checkBlockInfo() public view returns(uint256 createBlock, uint256 recentlyUsedBlock) {
return (_createBlock, _recentlyUsedBlock);
}
/**
* @dev Check owner's approved allowance to the spender
* @param owner Approving address
* @param spender Approved address
* @return Approved amount
*/
function allowance(address owner, address spender) override public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer method
* @param to Transfer target
* @param value Transfer amount
* @return Whether the transfer is successful
*/
function transfer(address to, uint256 value) override public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approval method
* @param spender Approval target
* @param value Approval amount
* @return Whether the approval is successful
*/
function approve(address spender, uint256 value) override public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens when approved
* @param from Transfer-out account address
* @param to Transfer-in account address
* @param value Transfer amount
* @return Whether approved transfer is successful
*/
function transferFrom(address from, address to, uint256 value) override public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
/**
* @dev Increase the allowance
* @param spender Approval target
* @param addedValue Amount to increase
* @return whether increase is successful
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the allowance
* @param spender Approval target
* @param subtractedValue Amount to decrease
* @return Whether decrease is successful
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer method
* @param to Transfer target
* @param value Transfer amount
*/
function _transfer(address from, address to, uint256 value) internal {
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Check the creator
* @return Creator address
*/
function checkBidder() public view returns(address) {
return _bidder;
}
/**
* @dev Transfer creator
* @param bidder New creator address
*/
function changeBidder(address bidder) public {
require(address(msg.sender) == _bidder);
_bidder = bidder;
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender));
_;
}
}
/**
* @title NToken mapping contract
* @dev Add, modify and check offering token mapping
*/
contract Nest_NToken_TokenMapping {
mapping (address => address) _tokenMapping; // Token mapping - offering token => NToken
Nest_3_VoteFactory _voteFactory; // Voting contract
event TokenMappingLog(address token, address nToken);
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor(address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
}
/**
* @dev Reset voting contract
* @param voteFactory voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner {
_voteFactory = Nest_3_VoteFactory(address(voteFactory));
}
/**
* @dev Add token mapping
* @param token Offering token address
* @param nToken Mining NToken address
*/
function addTokenMapping(address token, address nToken) public {
require(address(msg.sender) == address(_voteFactory.checkAddress("nest.nToken.tokenAuction")), "No authority");
require(_tokenMapping[token] == address(0x0), "Token already exists");
_tokenMapping[token] = nToken;
emit TokenMappingLog(token, nToken);
}
/**
* @dev Change token mapping
* @param token Offering token address
* @param nToken Mining NToken address
*/
function changeTokenMapping(address token, address nToken) public onlyOwner {
_tokenMapping[token] = nToken;
emit TokenMappingLog(token, nToken);
}
/**
* @dev Check token mapping
* @param token Offering token address
* @return Mining NToken address
*/
function checkTokenMapping(address token) public view returns (address) {
return _tokenMapping[token];
}
// Only for administrator
modifier onlyOwner(){
require(_voteFactory.checkOwners(msg.sender), "No authority");
_;
}
}
|
Check whether the address is in the blocklist
|
function checkBlocklist(address add) public view returns(bool) {
return _blocklist[add];
}
| 12,580,184
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
interface IAddressRegistry {
function auction() external view returns (address);
function marketplace() external view returns (address);
function tokenRegistry() external view returns (address);
}
interface IMarketplace {
function validateItemSold(
address,
uint256,
address,
address
) external;
function getPrice(address) external view returns (int256);
}
interface ITokenRegistry {
function enabled(address) external returns (bool);
}
contract BundleMarketplace is
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeMath for uint256;
using AddressUpgradeable for address payable;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.Bytes32Set;
/// @notice Events for the contract
event ItemListed(
address indexed owner,
string bundleID,
address payToken,
uint256 price,
uint256 startingTime
);
event ItemSold(
address indexed seller,
address indexed buyer,
string bundleID,
address payToken,
int256 unitPrice,
uint256 price
);
event ItemUpdated(
address indexed owner,
string bundleID,
address[] nft,
uint256[] tokenId,
uint256[] quantity,
address payToken,
uint256 newPrice
);
event ItemCanceled(address indexed owner, string bundleID);
event OfferCreated(
address indexed creator,
string bundleID,
address payToken,
uint256 price,
uint256 deadline
);
event OfferCanceled(address indexed creator, string bundleID);
event UpdatePlatformFee(uint256 platformFee);
event UpdatePlatformFeeRecipient(address payable platformFeeRecipient);
/// @notice Structure for Bundle Item Listing
struct Listing {
address[] nfts;
uint256[] tokenIds;
uint256[] quantities;
address payToken;
uint256 price;
uint256 startingTime;
}
/// @notice Structure for bundle offer
struct Offer {
IERC20 payToken;
uint256 price;
uint256 deadline;
}
bytes4 private constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant INTERFACE_ID_ERC1155 = 0xd9b67a26;
/// @notice Owner -> Bundle ID -> Bundle Listing item
mapping(address => mapping(bytes32 => Listing)) public listings;
/// @notice Bundle ID -> Wwner
mapping(bytes32 => address) public owners;
mapping(address => mapping(uint256 => EnumerableSet.Bytes32Set)) bundleIdsPerItem;
mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) nftIndexes;
mapping(bytes32 => string) bundleIds;
/// @notice Bundle ID -> Offerer -> Offer
mapping(bytes32 => mapping(address => Offer)) public offers;
/// @notice Platform fee
uint256 public platformFee;
/// @notice Platform fee receipient
address payable public feeReceipient;
/// @notice Address registry
IAddressRegistry public addressRegistry;
modifier onlyContract() {
require(
addressRegistry.auction() == _msgSender() ||
addressRegistry.marketplace() == _msgSender(),
"sender must be auction or marketplace"
);
_;
}
/// @notice Contract initializer
function initialize(address payable _feeRecipient, uint256 _platformFee)
public
initializer
{
platformFee = _platformFee;
feeReceipient = _feeRecipient;
__Ownable_init();
__ReentrancyGuard_init();
}
/// @notice Method for get NFT bundle listing
/// @param _owner Owner address
/// @param _bundleID Bundle ID
function getListing(address _owner, string memory _bundleID)
external
view
returns (
address[] memory nfts,
uint256[] memory tokenIds,
uint256[] memory quantities,
uint256 price,
uint256 startingTime
)
{
bytes32 bundleID = _getBundleID(_bundleID);
nfts = listings[_owner][bundleID].nfts;
tokenIds = listings[_owner][bundleID].tokenIds;
quantities = listings[_owner][bundleID].quantities;
price = listings[_owner][bundleID].price;
startingTime = listings[_owner][bundleID].startingTime;
}
/// @notice Method for listing NFT bundle
/// @param _bundleID Bundle ID
/// @param _nftAddresses Addresses of NFT contract
/// @param _tokenIds Token IDs of NFT
/// @param _quantities token amounts to list (needed for ERC-1155 NFTs, set as 1 for ERC-721)
/// @param _price sale price for bundle
/// @param _startingTime scheduling for a future sale
function listItem(
string memory _bundleID,
address[] calldata _nftAddresses,
uint256[] calldata _tokenIds,
uint256[] calldata _quantities,
address _payToken,
uint256 _price,
uint256 _startingTime
) external {
bytes32 bundleID = _getBundleID(_bundleID);
bundleIds[bundleID] = _bundleID;
require(
_nftAddresses.length == _tokenIds.length &&
_tokenIds.length == _quantities.length,
"invalid data"
);
require(
owners[bundleID] == address(0) ||
(owners[bundleID] == _msgSender() &&
listings[_msgSender()][bundleID].price == 0),
"already listed"
);
address tokenRegistry = addressRegistry.tokenRegistry();
require(
_payToken == address(0) ||
(tokenRegistry != address(0) &&
ITokenRegistry(tokenRegistry).enabled(_payToken)),
"invalid pay token"
);
Listing storage listing = listings[_msgSender()][bundleID];
delete listing.nfts;
delete listing.tokenIds;
delete listing.quantities;
for (uint256 i; i < _nftAddresses.length; i++) {
if (_supportsInterface(_nftAddresses[i], INTERFACE_ID_ERC721)) {
IERC721 nft = IERC721(_nftAddresses[i]);
_check721Owning(_nftAddresses[i], _tokenIds[i], _msgSender());
require(
nft.isApprovedForAll(_msgSender(), address(this)),
"item not approved"
);
listing.quantities.push(uint256(1));
} else if (
_supportsInterface(_nftAddresses[i], INTERFACE_ID_ERC1155)
) {
IERC1155 nft = IERC1155(_nftAddresses[i]);
_check1155Owning(
_nftAddresses[i],
_tokenIds[i],
_quantities[i],
_msgSender()
);
require(
nft.isApprovedForAll(_msgSender(), address(this)),
"item not approved"
);
listing.quantities.push(_quantities[i]);
} else {
revert("invalid nft address");
}
address _nft = _nftAddresses[i];
listing.nfts.push(_nft);
listing.tokenIds.push(_tokenIds[i]);
bundleIdsPerItem[_nft][_tokenIds[i]].add(bundleID);
nftIndexes[bundleID][_nft][_tokenIds[i]] = i;
}
listing.payToken = _payToken;
listing.price = _price;
listing.startingTime = _startingTime;
owners[bundleID] = _msgSender();
emit ItemListed(
_msgSender(),
_bundleID,
_payToken,
_price,
_startingTime
);
}
/// @notice Method for canceling listed NFT bundle
function cancelListing(string memory _bundleID) external nonReentrant {
bytes32 bundleID = _getBundleID(_bundleID);
require(listings[_msgSender()][bundleID].price > 0, "not listed");
_cancelListing(_msgSender(), _bundleID);
}
/// @notice Method for updating listed NFT bundle
/// @param _bundleID Bundle ID
/// @param _newPrice New sale price for bundle
function updateListing(
string memory _bundleID,
address _payToken,
uint256 _newPrice
) external nonReentrant {
bytes32 bundleID = _getBundleID(_bundleID);
Listing storage listing = listings[_msgSender()][bundleID];
require(listing.price > 0, "not listed");
address tokenRegistry = addressRegistry.tokenRegistry();
require(
_payToken == address(0) ||
(tokenRegistry != address(0) &&
ITokenRegistry(tokenRegistry).enabled(_payToken)),
"invalid pay token"
);
listing.payToken = _payToken;
listing.price = _newPrice;
emit ItemUpdated(
_msgSender(),
_bundleID,
listing.nfts,
listing.tokenIds,
listing.quantities,
_payToken,
_newPrice
);
}
/// @notice Method for buying listed NFT bundle
/// @param _bundleID Bundle ID
function buyItem(string memory _bundleID) external payable nonReentrant {
bytes32 bundleID = _getBundleID(_bundleID);
address owner = owners[bundleID];
require(owner != address(0), "invalid id");
Listing memory listing = listings[owner][bundleID];
require(listing.payToken == address(0), "invalid pay token");
require(msg.value >= listing.price, "insufficient balance to buy");
_buyItem(_bundleID, address(0));
}
/// @notice Method for buying listed NFT bundle
/// @param _bundleID Bundle ID
function buyItem(string memory _bundleID, address _payToken)
external
nonReentrant
{
bytes32 bundleID = _getBundleID(_bundleID);
address owner = owners[bundleID];
require(owner != address(0), "invalid id");
Listing memory listing = listings[owner][bundleID];
require(listing.payToken == _payToken, "invalid pay token");
_buyItem(_bundleID, _payToken);
}
function _buyItem(string memory _bundleID, address _payToken) private {
bytes32 bundleID = _getBundleID(_bundleID);
address owner = owners[bundleID];
Listing memory listing = listings[owner][bundleID];
require(listing.price > 0, "not listed");
for (uint256 i; i < listing.nfts.length; i++) {
if (_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC721)) {
_check721Owning(listing.nfts[i], listing.tokenIds[i], owner);
} else if (
_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC1155)
) {
_check1155Owning(
listing.nfts[i],
listing.tokenIds[i],
listing.quantities[i],
owner
);
}
}
require(_getNow() >= listing.startingTime, "not buyable");
uint256 price = listing.price;
uint256 feeAmount = price.mul(platformFee).div(1e3);
if (_payToken == address(0)) {
(bool feeTransferSuccess, ) = feeReceipient.call{value: feeAmount}(
""
);
require(
feeTransferSuccess,
"Marketplace: Fee transfer failed"
);
(bool ownerTransferSuccess, ) = owner.call{
value: price.sub(feeAmount)
}("");
require(
ownerTransferSuccess,
"Marketplace: Owner transfer failed"
);
} else {
IERC20(_payToken).safeTransferFrom(
_msgSender(),
feeReceipient,
feeAmount
);
IERC20(_payToken).safeTransferFrom(
_msgSender(),
owner,
price.sub(feeAmount)
);
}
// Transfer NFT to buyer
for (uint256 i; i < listing.nfts.length; i++) {
if (_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC721)) {
IERC721(listing.nfts[i]).safeTransferFrom(
owner,
_msgSender(),
listing.tokenIds[i]
);
} else {
IERC1155(listing.nfts[i]).safeTransferFrom(
owner,
_msgSender(),
listing.tokenIds[i],
listing.quantities[i],
bytes("")
);
}
IMarketplace(addressRegistry.marketplace()).validateItemSold(
listing.nfts[i],
listing.tokenIds[i],
owner,
_msgSender()
);
}
delete (listings[owner][bundleID]);
listing.price = 0;
listings[_msgSender()][bundleID] = listing;
owners[bundleID] = _msgSender();
delete (offers[bundleID][_msgSender()]);
emit ItemSold(
owner,
_msgSender(),
_bundleID,
_payToken,
IMarketplace(addressRegistry.marketplace()).getPrice(_payToken),
price
);
emit OfferCanceled(_msgSender(), _bundleID);
}
/// @notice Method for offering bundle item
/// @param _bundleID Bundle ID
/// @param _payToken Paying token
/// @param _price Price
/// @param _deadline Offer expiration
function createOffer(
string memory _bundleID,
IERC20 _payToken,
uint256 _price,
uint256 _deadline
) external {
bytes32 bundleID = _getBundleID(_bundleID);
require(owners[bundleID] != address(0), "invalid id");
require(_deadline > _getNow(), "invalid expiration");
require(_price > 0, "invalid price");
Offer memory offer = offers[bundleID][_msgSender()];
require(offer.deadline <= _getNow(), "offer exists");
offers[bundleID][_msgSender()] = Offer(_payToken, _price, _deadline);
emit OfferCreated(
_msgSender(),
_bundleID,
address(_payToken),
_price,
_deadline
);
}
/// @notice Method for canceling the offer
/// @param _bundleID Bundle ID
function cancelOffer(string memory _bundleID) external {
bytes32 bundleID = _getBundleID(_bundleID);
Offer memory offer = offers[bundleID][_msgSender()];
require(offer.deadline > _getNow(), "offer not exists or expired");
delete (offers[bundleID][_msgSender()]);
emit OfferCanceled(_msgSender(), _bundleID);
}
/// @notice Method for accepting the offer
function acceptOffer(string memory _bundleID, address _creator)
external
nonReentrant
{
bytes32 bundleID = _getBundleID(_bundleID);
require(owners[bundleID] == _msgSender(), "not owning item");
Offer memory offer = offers[bundleID][_creator];
require(offer.deadline > _getNow(), "offer not exists or expired");
uint256 price = offer.price;
uint256 feeAmount = price.mul(platformFee).div(1e3);
offer.payToken.safeTransferFrom(_creator, feeReceipient, feeAmount);
offer.payToken.safeTransferFrom(
_creator,
_msgSender(),
price.sub(feeAmount)
);
// Transfer NFT to buyer
Listing memory listing = listings[_msgSender()][bundleID];
for (uint256 i; i < listing.nfts.length; i++) {
if (_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC721)) {
IERC721(listing.nfts[i]).safeTransferFrom(
_msgSender(),
_creator,
listing.tokenIds[i]
);
} else {
IERC1155(listing.nfts[i]).safeTransferFrom(
_msgSender(),
_creator,
listing.tokenIds[i],
listing.quantities[i],
bytes("")
);
}
IMarketplace(addressRegistry.marketplace()).validateItemSold(
listing.nfts[i],
listing.tokenIds[i],
owners[bundleID],
_creator
);
}
delete (listings[_msgSender()][bundleID]);
listing.price = 0;
listings[_creator][bundleID] = listing;
owners[bundleID] = _creator;
delete (offers[bundleID][_creator]);
emit ItemSold(
_msgSender(),
_creator,
_bundleID,
address(offer.payToken),
IMarketplace(addressRegistry.marketplace()).getPrice(address(offer.payToken)),
offer.price
);
emit OfferCanceled(_creator, _bundleID);
}
/**
@notice Method for updating platform fee
@dev Only admin
@param _platformFee uint256 the platform fee to set
*/
function updatePlatformFee(uint256 _platformFee) external onlyOwner {
platformFee = _platformFee;
emit UpdatePlatformFee(_platformFee);
}
/**
@notice Method for updating platform fee address
@dev Only admin
@param _platformFeeRecipient payable address the address to sends the funds to
*/
function updatePlatformFeeRecipient(address payable _platformFeeRecipient)
external
onlyOwner
{
feeReceipient = _platformFeeRecipient;
emit UpdatePlatformFeeRecipient(_platformFeeRecipient);
}
/**
@notice Update AddressRegistry contract
@dev Only admin
*/
function updateAddressRegistry(address _registry) external onlyOwner {
addressRegistry = IAddressRegistry(_registry);
}
/**
* @notice Validate and cancel listing
* @dev Only marketplace can access
*/
function validateItemSold(
address _nftAddress,
uint256 _tokenId,
uint256 _quantity
) external onlyContract {
uint256 length = bundleIdsPerItem[_nftAddress][_tokenId].length();
for (uint256 i; i < length; i++) {
bytes32 bundleID = bundleIdsPerItem[_nftAddress][_tokenId].at(i);
address _owner = owners[bundleID];
if (_owner != address(0)) {
Listing storage listing = listings[_owner][bundleID];
string memory _bundleID = bundleIds[bundleID];
uint256 index = nftIndexes[bundleID][_nftAddress][_tokenId];
if (listing.quantities[index] > _quantity) {
listing.quantities[index] = listing.quantities[index].sub(
_quantity
);
} else {
delete (nftIndexes[bundleID][_nftAddress][_tokenId]);
if (listing.nfts.length == 1) {
delete (listings[_owner][bundleID]);
delete (owners[bundleID]);
delete (bundleIds[bundleID]);
emit ItemUpdated(
_owner,
_bundleID,
new address[](0),
new uint256[](0),
new uint256[](0),
address(0),
0
);
continue;
} else {
if (index < listing.nfts.length - 1) {
listing.nfts[index] = listing.nfts[
listing.nfts.length - 1
];
listing.tokenIds[index] = listing.tokenIds[
listing.tokenIds.length - 1
];
listing.quantities[index] = listing.quantities[
listing.quantities.length - 1
];
nftIndexes[bundleID][listing.nfts[index]][
listing.tokenIds[index]
] = index;
}
listing.nfts.pop();
listing.tokenIds.pop();
listing.quantities.pop();
}
}
emit ItemUpdated(
_owner,
_bundleID,
listing.nfts,
listing.tokenIds,
listing.quantities,
listing.payToken,
listing.price
);
}
}
delete (bundleIdsPerItem[_nftAddress][_tokenId]);
}
////////////////////////////
/// Internal and Private ///
////////////////////////////
function _supportsInterface(address _addr, bytes4 iface)
internal
view
returns (bool)
{
return IERC165(_addr).supportsInterface(iface);
}
function _check721Owning(
address _nft,
uint256 _tokenId,
address _owner
) internal view {
require(IERC721(_nft).ownerOf(_tokenId) == _owner, "not owning item");
}
function _check1155Owning(
address _nft,
uint256 _tokenId,
uint256 _quantity,
address _owner
) internal view {
require(
IERC1155(_nft).balanceOf(_owner, _tokenId) >= _quantity,
"not owning item"
);
}
function _getNow() internal view virtual returns (uint256) {
return block.timestamp;
}
function _cancelListing(address _owner, string memory _bundleID) private {
bytes32 bundleID = _getBundleID(_bundleID);
Listing memory listing = listings[_owner][bundleID];
for (uint256 i; i < listing.nfts.length; i++) {
bundleIdsPerItem[listing.nfts[i]][listing.tokenIds[i]].remove(
bundleID
);
delete (nftIndexes[bundleID][listing.nfts[i]][listing.tokenIds[i]]);
}
delete (listings[_owner][bundleID]);
delete (owners[bundleID]);
delete (bundleIds[bundleID]);
emit ItemCanceled(_owner, _bundleID);
}
function _getBundleID(string memory _bundleID)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_bundleID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
|
Method for updating listed NFT bundle _bundleID Bundle ID _newPrice New sale price for bundle
|
function updateListing(
string memory _bundleID,
address _payToken,
uint256 _newPrice
) external nonReentrant {
bytes32 bundleID = _getBundleID(_bundleID);
Listing storage listing = listings[_msgSender()][bundleID];
require(listing.price > 0, "not listed");
address tokenRegistry = addressRegistry.tokenRegistry();
require(
_payToken == address(0) ||
(tokenRegistry != address(0) &&
ITokenRegistry(tokenRegistry).enabled(_payToken)),
"invalid pay token"
);
listing.payToken = _payToken;
listing.price = _newPrice;
emit ItemUpdated(
_msgSender(),
_bundleID,
listing.nfts,
listing.tokenIds,
listing.quantities,
_payToken,
_newPrice
);
}
| 1,519,380
|
// SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* 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
*/
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "../../interfaces/IPendleData.sol";
import "../../interfaces/IPendleMarket.sol";
import "../../interfaces/IPendleForge.sol";
import "../../interfaces/IPendleMarketFactory.sol";
import "../../interfaces/IPendleYieldToken.sol";
import "../../tokens/PendleBaseToken.sol";
import "../../libraries/MathLib.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
abstract contract PendleMarketBase is IPendleMarket, PendleBaseToken {
using Math for uint256;
using SafeMath for uint256;
using SafeERC20 for IERC20;
address private immutable factory;
bytes32 public immutable override factoryId;
address internal immutable forge;
address public immutable override token;
address public immutable override xyt;
bool public bootstrapped;
string private constant NAME = "Pendle Market";
string private constant SYMBOL = "PENDLE-LPT";
uint256 private constant MINIMUM_LIQUIDITY = 10**3;
uint8 private constant DECIMALS = 18;
uint256 private priceLast = Math.RONE;
uint256 private blockNumLast;
uint256 private constant LN_PI_PLUSONE = 1562071538258; // this is equal to Math.ln(Math.PI_PLUSONE,Math.RONE)
uint256 internal paramL;
uint256 internal lastNYield;
mapping(address => uint256) internal lastParamL;
uint256 private constant MULTIPLIER = 10**20;
uint256 private reserveData;
uint256 private lastInterestUpdate;
uint256 private constant MASK_148_TO_255 = type(uint256).max ^ ((1 << 148) - 1);
uint256 private constant MASK_40_TO_147 = ((1 << 148) - 1) ^ ((1 << 40) - 1);
uint256 private constant MASK_0_TO_39 = ((1 << 40) - 1);
uint256 private constant MAX_TOKEN_RESERVE_BALANCE = (1 << 108) - 1;
// the lockStartTime is set at the bootstrap time of the market, and will not
// be changed for the entire market duration
uint256 public lockStartTime;
/* these variables are used often, so we get them once in the constructor
and save gas for retrieving them afterwards */
bytes32 private immutable forgeId;
address internal immutable underlyingAsset;
IERC20 private immutable underlyingYieldToken;
IPendleData private immutable data;
IPendleRouter private immutable router;
uint256 private immutable xytStartTime;
constructor(
address _forge,
address _xyt,
address _token,
uint256 _expiry
) PendleBaseToken(NAME, SYMBOL, DECIMALS, block.timestamp, _expiry) {
require(_xyt != address(0), "ZERO_ADDRESS");
require(_token != address(0), "ZERO_ADDRESS");
IPendleYieldToken xytContract = IPendleYieldToken(_xyt);
factory = msg.sender;
forge = _forge;
xyt = _xyt;
token = _token;
forgeId = IPendleForge(_forge).forgeId();
underlyingAsset = xytContract.underlyingAsset();
underlyingYieldToken = IERC20(IPendleYieldToken(_xyt).underlyingYieldToken());
expiry = _expiry;
address routerAddress = address(IPendleMarketFactory(msg.sender).router());
router = IPendleRouter(routerAddress);
data = IPendleForge(_forge).data();
xytStartTime = IPendleYieldToken(_xyt).start();
factoryId = IPendleMarketFactory(msg.sender).marketFactoryId();
_approve(address(this), routerAddress, type(uint256).max);
IERC20(_xyt).safeApprove(routerAddress, type(uint256).max);
IERC20(_token).safeApprove(routerAddress, type(uint256).max);
}
function checkIsBootstrapped() internal view {
require(bootstrapped, "NOT_BOOTSTRAPPED");
}
function checkOnlyRouter() internal view {
require(msg.sender == address(router), "ONLY_ROUTER");
}
function checkMarketIsOpen() internal view {
require(block.timestamp < lockStartTime, "MARKET_LOCKED");
}
function decodeReserveData(uint256 _reserveData)
internal
pure
returns (
uint256 xytBalance,
uint256 tokenBalance,
uint256 xytWeight,
uint256 tokenWeight
)
{
xytBalance = (_reserveData & MASK_148_TO_255) >> 148;
tokenBalance = (_reserveData & MASK_40_TO_147) >> 40;
xytWeight = _reserveData & MASK_0_TO_39;
tokenWeight = Math.RONE - xytWeight;
}
function parseTokenReserveData(address _asset, uint256 _reserveData)
internal
view
returns (TokenReserve memory tokenReserve)
{
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
decodeReserveData(_reserveData);
if (_asset == xyt) {
tokenReserve = TokenReserve(xytWeight, xytBalance);
} else {
tokenReserve = TokenReserve(tokenWeight, tokenBalance);
}
}
function dryUpdateReserveData(
TokenReserve memory tokenReserve,
address _asset,
uint256 oldReserveData
) internal view returns (uint256 _updatedReserveData) {
require(tokenReserve.balance <= MAX_TOKEN_RESERVE_BALANCE, "EXCEED_TOKEN_BALANCE_LIMIT");
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
decodeReserveData(oldReserveData);
if (_asset == xyt) {
(xytWeight, xytBalance) = (tokenReserve.weight, tokenReserve.balance);
} else {
(tokenWeight, tokenBalance) = (tokenReserve.weight, tokenReserve.balance);
xytWeight = Math.RONE.sub(tokenWeight);
}
_updatedReserveData = encodeReserveData(xytBalance, tokenBalance, xytWeight);
}
function encodeReserveData(
uint256 xytBalance,
uint256 tokenBalance,
uint256 xytWeight
) internal pure returns (uint256 _updatedReserveData) {
require(xytBalance <= MAX_TOKEN_RESERVE_BALANCE, "EXCEED_TOKEN_BALANCE_LIMIT");
require(tokenBalance <= MAX_TOKEN_RESERVE_BALANCE, "EXCEED_TOKEN_BALANCE_LIMIT");
_updatedReserveData = (xytBalance << 148) | (tokenBalance << 40) | xytWeight;
}
function bootstrap(uint256 initialXytLiquidity, uint256 initialTokenLiquidity)
external
override
returns (PendingTransfer[3] memory transfers)
{
checkOnlyRouter();
require(!bootstrapped, "ALREADY_BOOTSTRAPPED");
_initializeLock(); // market's lock params should be initialized at bootstrap time
reserveData = encodeReserveData(initialXytLiquidity, initialTokenLiquidity, Math.RONE / 2);
emit Sync(initialXytLiquidity, Math.RONE / 2, initialTokenLiquidity);
uint256 liquidity =
Math.sqrt(initialXytLiquidity.mul(initialTokenLiquidity)).sub(MINIMUM_LIQUIDITY);
_mintLp(MINIMUM_LIQUIDITY.add(liquidity));
transfers[0].amount = initialXytLiquidity;
transfers[0].isOut = false;
transfers[1].amount = initialTokenLiquidity;
transfers[1].isOut = false;
transfers[2].amount = liquidity;
transfers[2].isOut = true;
blockNumLast = block.number;
bootstrapped = true;
_afterBootstrap();
}
/**
* @notice Join the market by putting in xytToken and pairTokens
* and get back desired amount of lpToken.
* @dev no curveShift to save gas because this function
doesn't depend on weights of tokens
*/
function addMarketLiquidityAll(
uint256 _exactOutLp,
uint256 _maxInXyt,
uint256 _maxInToken
) external override returns (PendingTransfer[3] memory transfers) {
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
_updateParamL();
uint256 totalLp = totalSupply;
uint256 ratio = Math.rdiv(_exactOutLp, totalLp);
require(ratio != 0, "ZERO_RATIO");
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(reserveData);
// Calc and inject XYT token.
uint256 amountXytUsed = Math.rmul(ratio, xytBalance);
require(amountXytUsed != 0, "ZERO_XYT_IN_AMOUNT");
require(amountXytUsed <= _maxInXyt, "LOW_XYT_IN_LIMIT");
xytBalance = xytBalance.add(amountXytUsed);
transfers[0].amount = amountXytUsed;
transfers[0].isOut = false;
// Calc and inject pair token.
uint256 amountTokenUsed = Math.rmul(ratio, tokenBalance);
require(amountTokenUsed != 0, "ZERO_TOKEN_IN_AMOUNT");
require(amountTokenUsed <= _maxInToken, "LOW_TOKEN_IN_LIMIT");
tokenBalance = tokenBalance.add(amountTokenUsed);
transfers[1].amount = amountTokenUsed;
transfers[1].isOut = false;
reserveData = encodeReserveData(xytBalance, tokenBalance, xytWeight);
emit Sync(xytBalance, xytWeight, tokenBalance);
// Mint and push LP token.
_mintLp(_exactOutLp);
transfers[2].amount = _exactOutLp;
transfers[2].isOut = true;
}
/**
* @notice Join the market by specifying the desired (and max) amount of xyts
* and tokens to put in.
* @param _desiredXytAmount amount of XYTs user wants to contribute
* @param _desiredTokenAmount amount of tokens user wants to contribute
* @param _xytMinAmount min amount of XYTs user wants to be able to contribute
* @param _tokenMinAmount min amount of tokens user wants to be able to contribute
* @dev no curveShift to save gas because this function
doesn't depend on weights of tokens
*/
function addMarketLiquidityDual(
uint256 _desiredXytAmount,
uint256 _desiredTokenAmount,
uint256 _xytMinAmount,
uint256 _tokenMinAmount
) external override returns (PendingTransfer[3] memory transfers, uint256 lpOut) {
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(reserveData);
uint256 amountXytUsed;
uint256 amountTokenUsed = _desiredXytAmount.mul(tokenBalance).div(xytBalance);
if (amountTokenUsed <= _desiredTokenAmount) {
// using _desiredXytAmount to determine the LP and add liquidity
require(amountTokenUsed >= _tokenMinAmount, "INSUFFICIENT_TOKEN_AMOUNT");
amountXytUsed = _desiredXytAmount;
lpOut = _desiredXytAmount.mul(totalSupply).div(xytBalance);
} else {
// using _desiredTokenAmount to determine the LP and add liquidity
amountXytUsed = _desiredTokenAmount.mul(xytBalance).div(tokenBalance);
require(amountXytUsed >= _xytMinAmount, "INSUFFICIENT_XYT_AMOUNT");
amountTokenUsed = _desiredTokenAmount;
lpOut = _desiredTokenAmount.mul(totalSupply).div(tokenBalance);
}
xytBalance = xytBalance.add(amountXytUsed);
transfers[0].amount = amountXytUsed;
transfers[0].isOut = false;
tokenBalance = tokenBalance.add(amountTokenUsed);
transfers[1].amount = amountTokenUsed;
transfers[1].isOut = false;
reserveData = encodeReserveData(xytBalance, tokenBalance, xytWeight);
emit Sync(xytBalance, xytWeight, tokenBalance);
// Mint and push LP token.
_mintLp(lpOut);
transfers[2].amount = lpOut;
transfers[2].isOut = true;
}
function addMarketLiquiditySingle(
address _inToken,
uint256 _exactIn,
uint256 _minOutLp
) external override returns (PendingTransfer[3] memory transfers) {
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
uint256 updatedReserveData = _curveShift();
_updateParamL();
TokenReserve memory inTokenReserve = parseTokenReserveData(_inToken, updatedReserveData);
uint256 totalLp = totalSupply;
// Calc out amount of LP token.
uint256 exactOutLp = _calcOutAmountLp(_exactIn, inTokenReserve, data.swapFee(), totalLp);
require(exactOutLp >= _minOutLp, "HIGH_LP_OUT_LIMIT");
// Update reserves and operate underlying LP and inToken.
inTokenReserve.balance = inTokenReserve.balance.add(_exactIn);
transfers[0].amount = _exactIn;
transfers[0].isOut = false;
// Mint and push LP token.
_mintLp(exactOutLp);
transfers[2].amount = exactOutLp;
transfers[2].isOut = true;
// repack data
updatedReserveData = dryUpdateReserveData(inTokenReserve, _inToken, updatedReserveData);
reserveData = updatedReserveData;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(updatedReserveData); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
/**
* @notice Exit the market by putting in the desired amount of LP tokens
* and getting back XYT and pair tokens.
* @dev With remove liquidity functions, LPs are always transfered in
* first in the Router, to make sure we have enough LPs in the market to burn
* as such, we don't need to set transfers[2]
* @dev no curveShift to save gas because this function
doesn't depend on weights of tokens
* @dev this function will never be locked since we always let users withdraw
their funds
*/
function removeMarketLiquidityAll(
uint256 _inLp,
uint256 _minOutXyt,
uint256 _minOutToken
) external override returns (PendingTransfer[3] memory transfers) {
checkIsBootstrapped();
checkOnlyRouter();
_updateParamL();
uint256 exitFee = data.exitFee();
uint256 totalLp = totalSupply;
uint256 exitFees = Math.rmul(_inLp, exitFee);
uint256 inLpAfterExitFee = _inLp.sub(exitFee);
uint256 ratio = Math.rdiv(inLpAfterExitFee, totalLp);
require(ratio != 0, "ZERO_RATIO");
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(reserveData); // unpack data
// Calc and withdraw xyt token.
uint256 balanceToken = xytBalance;
uint256 xytOut = Math.rmul(ratio, balanceToken);
require(xytOut != 0, "MATH_ERROR");
require(xytOut >= _minOutXyt, "INSUFFICIENT_XYT_OUT");
xytBalance = xytBalance.sub(xytOut);
transfers[0].amount = xytOut;
transfers[0].isOut = true;
// Calc and withdraw pair token.
balanceToken = tokenBalance;
uint256 tokenOut = Math.rmul(ratio, balanceToken);
require(tokenOut != 0, "MATH_ERROR");
require(tokenOut >= _minOutToken, "INSUFFICIENT_TOKEN_OUT");
tokenBalance = tokenBalance.sub(tokenOut);
transfers[1].amount = tokenOut;
transfers[1].isOut = true;
reserveData = encodeReserveData(xytBalance, tokenBalance, xytWeight); // repack data
emit Sync(xytBalance, xytWeight, tokenBalance);
// Deal with lp last.
_collectFees(exitFees);
_burnLp(inLpAfterExitFee);
}
/// @dev With remove liquidity functions, LPs are always transfered in
/// first in the Router, to make sure we have enough LPs in the market to burn
/// as such, we don't need to set transfers[2]
function removeMarketLiquiditySingle(
address _outToken,
uint256 _inLp,
uint256 _minOutAmountToken
) external override returns (PendingTransfer[3] memory transfers) {
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
uint256 updatedReserveData = _curveShift();
_updateParamL();
TokenReserve memory outTokenReserve = parseTokenReserveData(_outToken, updatedReserveData);
uint256 exitFee = data.exitFee();
uint256 exitFees = Math.rmul(_inLp, data.exitFee());
uint256 totalLp = totalSupply;
uint256 outAmountToken = _calcOutAmountToken(outTokenReserve, totalLp, _inLp);
require(outAmountToken >= _minOutAmountToken, "INSUFFICIENT_TOKEN_OUT");
// Update reserves and operate underlying LP and outToken
outTokenReserve.balance = outTokenReserve.balance.sub(outAmountToken);
updatedReserveData = dryUpdateReserveData(outTokenReserve, _outToken, updatedReserveData);
reserveData = updatedReserveData;
_collectFees(exitFee);
_burnLp(_inLp.sub(exitFees));
transfers[0].amount = outAmountToken;
transfers[0].isOut = true;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(updatedReserveData); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
}
function swapExactIn(
address inToken,
uint256 inAmount,
address outToken,
uint256 minOutAmount,
uint256 maxPrice
)
external
override
returns (
uint256 outAmount,
uint256 spotPriceAfter,
PendingTransfer[3] memory transfers
)
{
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
uint256 updatedReserveData = _curveShift();
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken, updatedReserveData);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken, updatedReserveData);
uint256 spotPriceBefore = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceBefore <= maxPrice, "LOW_MAX_PRICE");
// calc out amount of token to be swapped out
outAmount = calcExactOut(inTokenReserve, outTokenReserve, inAmount, data.swapFee());
require(outAmount >= minOutAmount, "HIGH_OUT_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
spotPriceAfter = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceAfter >= spotPriceBefore, "MATH_ERROR");
require(spotPriceAfter <= maxPrice, "LOW_MAX_PRICE");
require(spotPriceBefore <= Math.rdiv(inAmount, outAmount), "MATH_ERROR");
// repack data
updatedReserveData = dryUpdateReserveData(inTokenReserve, inToken, updatedReserveData);
updatedReserveData = dryUpdateReserveData(outTokenReserve, outToken, updatedReserveData);
reserveData = updatedReserveData;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(updatedReserveData); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
}
function swapExactOut(
address inToken,
uint256 maxInAmount,
address outToken,
uint256 outAmount,
uint256 maxPrice
)
external
override
returns (
uint256 inAmount,
uint256 spotPriceAfter,
PendingTransfer[3] memory transfers
)
{
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
uint256 updatedReserveData = _curveShift();
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken, updatedReserveData);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken, updatedReserveData);
// Calc spot price.
uint256 spotPriceBefore = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceBefore <= maxPrice, "LOW_MAX_PRICE");
// Calc in amount.
inAmount = calcExactIn(inTokenReserve, outTokenReserve, outAmount, data.swapFee());
require(inAmount <= maxInAmount, "LOW_IN_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
spotPriceAfter = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceAfter >= spotPriceBefore, "MATH_ERROR");
require(spotPriceAfter <= maxPrice, "LOW_MAX_PRICE");
require(spotPriceBefore <= Math.rdiv(inAmount, outAmount), "MATH_ERROR");
// repack data
updatedReserveData = dryUpdateReserveData(inTokenReserve, inToken, updatedReserveData);
updatedReserveData = dryUpdateReserveData(outTokenReserve, outToken, updatedReserveData);
reserveData = updatedReserveData;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
decodeReserveData(updatedReserveData); // unpack data
emit Sync(xytBalance, xytWeight, tokenBalance);
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
}
function claimLpInterests(address account) external override returns (uint256 interests) {
checkIsBootstrapped();
checkOnlyRouter();
interests = _settleLpInterests(account);
}
function getReserves()
external
view
override
returns (
uint256 xytBalance,
uint256 xytWeight,
uint256 tokenBalance,
uint256 tokenWeight,
uint256 lastUpdatedBlock
)
{
// get the weight right now of the market, not the weight of the last update
(xytWeight, tokenWeight, ) = _updateWeightDry(reserveData, priceLast);
(xytBalance, tokenBalance, , ) = decodeReserveData(reserveData);
lastUpdatedBlock = blockNumLast;
}
function calcExactIn(
TokenReserve memory inTokenReserve,
TokenReserve memory outTokenReserve,
uint256 exactOut,
uint256 swapFee
) public pure override returns (uint256 exactIn) {
uint256 weightRatio = Math.rdiv(outTokenReserve.weight, inTokenReserve.weight);
uint256 diff = outTokenReserve.balance.sub(exactOut);
uint256 y = Math.rdiv(outTokenReserve.balance, diff);
uint256 foo = Math.rpow(y, weightRatio);
foo = foo.sub(Math.RONE);
exactIn = Math.RONE.sub(swapFee);
exactIn = Math.rdiv(Math.rmul(inTokenReserve.balance, foo), exactIn);
}
function calcExactOut(
TokenReserve memory inTokenReserve,
TokenReserve memory outTokenReserve,
uint256 exactIn,
uint256 swapFee
) public pure override returns (uint256 exactOut) {
uint256 weightRatio = Math.rdiv(inTokenReserve.weight, outTokenReserve.weight);
uint256 adjustedIn = Math.RONE.sub(swapFee);
adjustedIn = Math.rmul(exactIn, adjustedIn);
uint256 y = Math.rdiv(inTokenReserve.balance, inTokenReserve.balance.add(adjustedIn));
uint256 foo = Math.rpow(y, weightRatio);
uint256 bar = Math.RONE.sub(foo);
exactOut = Math.rmul(outTokenReserve.balance, bar);
}
function spotPrice(address inToken, address outToken)
external
view
override
returns (uint256 spot)
{
uint256 localReserveData = reserveData;
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken, localReserveData);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken, localReserveData);
return _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
}
function _calcSpotPrice(
TokenReserve memory inTokenReserve,
TokenReserve memory outTokenReserve,
uint256 swapFee
) internal pure returns (uint256 spot) {
uint256 numer = Math.rdiv(inTokenReserve.balance, inTokenReserve.weight);
uint256 denom = Math.rdiv(outTokenReserve.balance, outTokenReserve.weight);
uint256 ratio = Math.rdiv(numer, denom);
uint256 scale = Math.rdiv(Math.RONE, Math.RONE.sub(swapFee));
spot = Math.rmul(ratio, scale);
}
function _calcOutAmountLp(
uint256 inAmount,
TokenReserve memory inTokenReserve,
uint256 swapFee,
uint256 totalSupplyLp
) internal pure returns (uint256 exactOutLp) {
uint256 nWeight = inTokenReserve.weight;
uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), swapFee);
uint256 inAmoutAfterFee = Math.rmul(inAmount, Math.RONE.sub(feePortion));
uint256 inBalanceUpdated = inTokenReserve.balance.add(inAmoutAfterFee);
uint256 inTokenRatio = Math.rdiv(inBalanceUpdated, inTokenReserve.balance);
uint256 lpTokenRatio = Math.rpow(inTokenRatio, nWeight);
uint256 totalSupplyLpUpdated = Math.rmul(lpTokenRatio, totalSupplyLp);
exactOutLp = totalSupplyLpUpdated.sub(totalSupplyLp);
return exactOutLp;
}
function _calcOutAmountToken(
TokenReserve memory outTokenReserve,
uint256 totalSupplyLp,
uint256 inLp
) internal view returns (uint256 exactOutToken) {
uint256 nWeight = outTokenReserve.weight;
uint256 inLpAfterExitFee = Math.rmul(inLp, Math.RONE.sub(data.exitFee()));
uint256 totalSupplyLpUpdated = totalSupplyLp.sub(inLpAfterExitFee);
uint256 lpRatio = Math.rdiv(totalSupplyLpUpdated, totalSupplyLp);
uint256 outTokenRatio = Math.rpow(lpRatio, Math.rdiv(Math.RONE, nWeight));
uint256 outTokenBalanceUpdated = Math.rmul(outTokenRatio, outTokenReserve.balance);
uint256 outAmountTOkenBeforeSwapFee = outTokenReserve.balance.sub(outTokenBalanceUpdated);
uint256 feePortion = Math.rmul(Math.RONE.sub(nWeight), data.swapFee());
exactOutToken = Math.rmul(outAmountTOkenBeforeSwapFee, Math.RONE.sub(feePortion));
return exactOutToken;
}
/// @notice Sends fees as LP to Treasury
function _collectFees(uint256 _amount) internal {
IERC20(address(this)).transfer(data.treasury(), _amount);
}
function _burnLp(uint256 amount) internal {
_burn(address(this), amount);
}
function _mintLp(uint256 amount) internal {
_mint(address(this), amount);
}
/**
* @notice update the priceLast & emit event, but not the real weight
* @dev this function read the reserveData directly from storage. But the reserveData is guaranteed
not to be obsolete because:
* this function will be called at most ONCE in every transaction
* all functions that call this function will eventually update the reserveData
=> it doesn't matter if the reserveData gets updated immediately or not
*/
function _updateWeightPartial() internal returns (uint256 updatedReserveData) {
updatedReserveData = reserveData;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
decodeReserveData(updatedReserveData); // unpack data
(uint256 xytWeightUpdated, , uint256 priceNow) =
_updateWeightDry(updatedReserveData, priceLast);
updatedReserveData = encodeReserveData(xytBalance, tokenBalance, xytWeightUpdated); // repack data
priceLast = priceNow;
// the weight is not updated yet, but all functions that call curveShift will eventually update the weight, so we just emit event first
emit Shift(xytWeight, tokenWeight, xytWeightUpdated);
}
// do the weight update calucation but don't update the token reserve memory
function _updateWeightDry(uint256 _reserveData, uint256 _priceLast)
internal
view
returns (
uint256 xytWeightUpdated,
uint256 tokenWeightUpdated,
uint256 priceNow
)
{
// get current timestamp currentTime
uint256 currentTime = block.timestamp;
uint256 endTime = expiry;
uint256 startTime = xytStartTime;
uint256 duration = endTime - startTime;
(, , uint256 xytWeight, uint256 tokenWeight) = decodeReserveData(_reserveData); // unpack data
uint256 timeLeft;
if (endTime >= currentTime) {
timeLeft = endTime - currentTime;
} else {
timeLeft = 0;
}
// get time_to_mature = (endTime - currentTime) / (endTime - startTime)
uint256 timeToMature = Math.rdiv(timeLeft * Math.RONE, duration * Math.RONE);
// get price for now = ln(3.14 * t + 1) / ln(4.14)
priceNow = Math.rdiv(
Math.ln(Math.rmul(Math.PI, timeToMature).add(Math.RONE), Math.RONE),
LN_PI_PLUSONE
);
uint256 r = Math.rdiv(priceNow, _priceLast);
require(Math.RONE >= r, "MATH_ERROR");
uint256 thetaNumerator = Math.rmul(Math.rmul(xytWeight, tokenWeight), Math.RONE.sub(r));
uint256 thetaDenominator = Math.rmul(r, xytWeight).add(tokenWeight);
// calc weight changes theta
uint256 theta = Math.rdiv(thetaNumerator, thetaDenominator);
xytWeightUpdated = xytWeight.sub(theta);
tokenWeightUpdated = tokenWeight.add(theta);
}
//curve shift will be called before any calculation using weight
function _curveShift() internal returns (uint256 updatedReserveData) {
if (block.number > blockNumLast) {
updatedReserveData = _updateWeightPartial();
blockNumLast = block.number;
} else {
updatedReserveData = reserveData;
}
}
function _settleLpInterests(address account) internal returns (uint256 dueInterests) {
if (account == address(this)) return 0;
_updateParamL();
uint256 interestValuePerLP = _getInterestValuePerLP(account);
if (interestValuePerLP == 0) return 0;
dueInterests = balanceOf[account].mul(interestValuePerLP).div(MULTIPLIER);
if (dueInterests == 0) {
return 0;
}
lastNYield = lastNYield.sub(dueInterests);
underlyingYieldToken.transfer(account, dueInterests);
}
// this function should be called whenver the total amount of LP changes
function _updateParamL() internal {
if (block.timestamp.sub(lastInterestUpdate) > data.interestUpdateDelta()) {
// get due interests for the XYT being held in the market if it has not been updated
// for interestUpdateDelta seconds
router.redeemDueInterests(forgeId, underlyingAsset, expiry);
lastInterestUpdate = block.timestamp;
}
uint256 currentNYield = underlyingYieldToken.balanceOf(address(this));
(uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(currentNYield);
uint256 secondTerm;
// this should always satisfy
if (paramR != 0 && totalSupply != 0) {
secondTerm = paramR.mul(MULTIPLIER).div(totalSupply);
}
// update new states
paramL = firstTerm.add(secondTerm);
lastNYield = currentNYield;
}
// before we send LPs, we need to settle due interests for both the to and from addresses
function _beforeTokenTransfer(address from, address to) internal override {
_settleLpInterests(from);
_settleLpInterests(to);
}
function _initializeLock() internal {
uint256 duration = expiry - xytStartTime; // market expiry = xyt expiry
uint256 lockDuration = (duration * data.lockNumerator()) / data.lockDenominator();
lockStartTime = expiry - lockDuration;
}
function _afterBootstrap() internal virtual {}
function _getInterestValuePerLP(address account)
internal
virtual
returns (uint256 interestValuePerLP)
{}
function _getFirstTermAndParamR(uint256 currentNYield)
internal
virtual
returns (uint256 firstTerm, uint256 paramR)
{}
}
|
Calc spot price. Calc in amount. repack data
|
function swapExactOut(
address inToken,
uint256 maxInAmount,
address outToken,
uint256 outAmount,
uint256 maxPrice
)
external
override
returns (
uint256 inAmount,
uint256 spotPriceAfter,
PendingTransfer[3] memory transfers
)
{
checkIsBootstrapped();
checkOnlyRouter();
checkMarketIsOpen();
uint256 updatedReserveData = _curveShift();
TokenReserve memory inTokenReserve = parseTokenReserveData(inToken, updatedReserveData);
TokenReserve memory outTokenReserve = parseTokenReserveData(outToken, updatedReserveData);
uint256 spotPriceBefore = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceBefore <= maxPrice, "LOW_MAX_PRICE");
inAmount = calcExactIn(inTokenReserve, outTokenReserve, outAmount, data.swapFee());
require(inAmount <= maxInAmount, "LOW_IN_LIMIT");
inTokenReserve.balance = inTokenReserve.balance.add(inAmount);
outTokenReserve.balance = outTokenReserve.balance.sub(outAmount);
spotPriceAfter = _calcSpotPrice(inTokenReserve, outTokenReserve, data.swapFee());
require(spotPriceAfter >= spotPriceBefore, "MATH_ERROR");
require(spotPriceAfter <= maxPrice, "LOW_MAX_PRICE");
require(spotPriceBefore <= Math.rdiv(inAmount, outAmount), "MATH_ERROR");
updatedReserveData = dryUpdateReserveData(inTokenReserve, inToken, updatedReserveData);
updatedReserveData = dryUpdateReserveData(outTokenReserve, outToken, updatedReserveData);
reserveData = updatedReserveData;
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, ) =
emit Sync(xytBalance, xytWeight, tokenBalance);
transfers[0].amount = inAmount;
transfers[0].isOut = false;
transfers[1].amount = outAmount;
transfers[1].isOut = true;
}
| 2,543,237
|
pragma solidity >=0.4.21 <0.7.0;
contract DeFeed {
string public name= "DeFeed";
uint storedData;
// function set(uint x) public {
// storedData = x;
// }
// function get() public view returns (uint) {
// return storedData;
// }
// Storing Posts
uint public postCount= 0;
mapping(uint => Post) public posts;
struct Post {
uint id;
string hash;
string description;
uint donation;
address payable author;
}
event postCreated(
uint id,
string hash,
string description,
uint donation,
address payable author
);
event postDonation(
uint id,
string hash,
string description,
uint donation,
address payable author
);
// Creating Posts
function uploadPost(string memory postHash, string memory description) public {
// Validations
require(bytes(postHash).length > 0); // Checking if Post Hash Exists
require(bytes(description).length > 0); // Checking if Post Description Exists
require(msg.sender != address(0x0)); // Checking if Uploader Address Exists
// Incrementing Post Count
postCount ++;
// Adding Posts to contract
posts[postCount]= Post(postCount, postHash, description, 0, msg.sender);
// Event Triggering
emit postCreated(postCount, postHash, description, 0, msg.sender);
}
// Donating
function donatePostAuthor(uint id) public payable {
require(id > 0 && id <= postCount);
// Fetch Post
Post memory post= posts[id];
address payable author= post.author;
//Paying Author with Ether
address(author).transfer(msg.value);
// Increment the Donation Amount
post.donation= post.donation + msg.value;
// Update the Post
posts[id]= post;
// Event Triggering
emit postDonation(id, post.hash, post.description, post.donation, author);
}
}
|
Donating Fetch PostPaying Author with Ether Increment the Donation Amount Update the Post Event Triggering
|
function donatePostAuthor(uint id) public payable {
require(id > 0 && id <= postCount);
Post memory post= posts[id];
address payable author= post.author;
address(author).transfer(msg.value);
post.donation= post.donation + msg.value;
posts[id]= post;
emit postDonation(id, post.hash, post.description, post.donation, author);
}
| 6,343,191
|
./full_match/42/0x28D2288e605A077DBfD8A23E77a41Af1B923BE0c/sources/browser/FluxCampacitar.sol
|
Set rewards portion in store balance. ex: 10 => 10%/
|
function setRewardPortion(uint256 rewardPortion)
external
onlyOwner
returns (bool)
{
require(
rewardPortion >= 10 && rewardPortion <= 100,
"FluxCampacitor: reward portion should be in 10 ~ 100."
);
_rewardPortion = rewardPortion;
return true;
}
| 9,585,895
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
interface IndexInterface {
function master() external view returns (address);
}
interface ConnectorsInterface {
function chief(address) external view returns (bool);
}
contract InstaMappingController is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
mapping(address => EnumerableSet.AddressSet) private _roles;
IndexInterface public constant instaIndex =
IndexInterface(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
ConnectorsInterface public constant connectors =
ConnectorsInterface(0x97b0B3A8bDeFE8cB9563a3c610019Ad10DB8aD11); // InstaConnectorsV2
/**
* @dev Emitted when `account` is granted `role`.
*/
event RoleGranted(address indexed role, address indexed account);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the insta master
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(
address indexed role,
address indexed account,
address indexed sender
);
modifier onlyMaster {
require(
instaIndex.master() == _msgSender() || connectors.chief(_msgSender()),
"MappingController: sender must be master or chief"
);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(address role, address account) public view returns (bool) {
return _roles[role].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(address role) public view returns (uint256) {
return _roles[role].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(address role, uint256 index)
public
view
returns (address)
{
return _roles[role].at(index);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must be the master.
*/
function grantRole(address role, address account)
public
virtual
onlyMaster
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must be the master.
*/
function revokeRole(address role, address account)
public
virtual
onlyMaster
{
_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(address role, address account) public virtual {
require(
account == _msgSender(),
"MappingController: 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(address role, address account) internal virtual {
_grantRole(role, account);
}
function _grantRole(address role, address account) private {
if (_roles[role].add(account)) {
emit RoleGranted(role, account);
}
}
function _revokeRole(address role, address account) private {
if (_roles[role].remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
|
Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must be the master./
|
function revokeRole(address role, address account)
public
virtual
onlyMaster
{
_revokeRole(role, account);
}
| 2,576,668
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface CTokenInterface {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); // For ERC20
function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address owner) external view returns (uint256 balance);
}
interface CETHInterface {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
function liquidateBorrow(address borrower, address cTokenCollateral) external payable;
}
interface TokenInterface {
function allowance(address, address) external view returns (uint);
function balanceOf(address) external view returns (uint);
function approve(address, uint) external;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
}
interface ComptrollerInterface {
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cTokenAddress) external returns (uint);
function getAssetsIn(address account) external view returns (address[] memory);
function getAccountLiquidity(address account) external view returns (uint, uint, uint);
function claimComp(address) external;
}
interface InstaMappingV2 {
function getMapping(string calldata tokenId) external view returns (address, address);
}
interface MemoryInterface {
function getUint(uint _id) external returns (uint _num);
function setUint(uint _id, uint _val) external;
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
}
contract Helpers is DSMath {
/**
* @dev Return ethereum address
*/
function getAddressETH() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Return Memory Variable Address
*/
function getMemoryAddr() internal pure returns (address) {
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address
}
// /**
// * @dev Return InstaEvent Address.
// */
// function getEventAddr() internal pure returns (address) {
// return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address
// }
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
/**
* @dev Connector Details
*/
function connectorID() public pure returns(uint _type, uint _id) {
(_type, _id) = (1, 57);
}
}
contract CompoundHelpers is Helpers {
/**
* @dev Return Compound Comptroller Address
*/
function getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
/**
* @dev Return COMP Token Address.
*/
function getCompTokenAddress() internal pure returns (address) {
return 0xc00e94Cb662C3520282E6f5717214004A7f26888;
}
/**
* @dev Return InstaDApp Mapping Addresses
*/
function getMappingAddr() internal pure returns (address) {
return 0xA8F9D4aA7319C54C04404765117ddBf9448E2082; // InstaMapping Address
}
/**
* @dev enter compound market
*/
function enterMarket(address cToken) internal {
ComptrollerInterface troller = ComptrollerInterface(getComptrollerAddress());
address[] memory markets = troller.getAssetsIn(address(this));
bool isEntered = false;
for (uint i = 0; i < markets.length; i++) {
if (markets[i] == cToken) {
isEntered = true;
}
}
if (!isEntered) {
address[] memory toEnter = new address[](1);
toEnter[0] = cToken;
troller.enterMarkets(toEnter);
}
}
}
contract BasicResolver is CompoundHelpers {
event LogDeposit(address indexed token, string tokenId, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogWithdraw(address indexed token, string tokenId, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogBorrow(address indexed token, string tokenId, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogPayback(address indexed token, string tokenId, address cToken, uint256 tokenAmt, uint256 getId, uint256 setId);
/**
* @dev Deposit ETH/ERC20_Token.
* @param tokenId token id of the token to deposit.(For eg: ETH-A)
* @param amt token amount to deposit.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function deposit(string calldata tokenId, uint amt, uint getId, uint setId) external payable{
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
enterMarket(cToken);
if (token == getAddressETH()) {
_amt = _amt == uint(-1) ? address(this).balance : _amt;
CETHInterface(cToken).mint.value(_amt)();
} else {
TokenInterface tokenContract = TokenInterface(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
tokenContract.approve(cToken, _amt);
require(CTokenInterface(cToken).mint(_amt) == 0, "deposit-failed");
}
setUint(setId, _amt);
emit LogDeposit(token, tokenId, cToken, _amt, getId, setId);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param tokenId token id of the token to withdraw.(For eg: ETH-A)
* @param amt token amount to withdraw.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdraw(string calldata tokenId, uint amt, uint getId, uint setId) external payable{
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
CTokenInterface cTokenContract = CTokenInterface(cToken);
if (_amt == uint(-1)) {
TokenInterface tokenContract = TokenInterface(token);
uint initialBal = token == getAddressETH() ? address(this).balance : tokenContract.balanceOf(address(this));
require(cTokenContract.redeem(cTokenContract.balanceOf(address(this))) == 0, "full-withdraw-failed");
uint finalBal = token == getAddressETH() ? address(this).balance : tokenContract.balanceOf(address(this));
_amt = finalBal - initialBal;
} else {
require(cTokenContract.redeemUnderlying(_amt) == 0, "withdraw-failed");
}
setUint(setId, _amt);
emit LogWithdraw(token, tokenId, cToken, _amt, getId, setId);
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param tokenId token id of the token to borrow.(For eg: DAI-A)
* @param amt token amount to borrow.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function borrow(string calldata tokenId, uint amt, uint getId, uint setId) external payable {
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
enterMarket(cToken);
require(CTokenInterface(cToken).borrow(_amt) == 0, "borrow-failed");
setUint(setId, _amt);
emit LogBorrow(token, tokenId, cToken, _amt, getId, setId);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param tokenId token id of the token to payback.(For eg: COMP-A)
* @param amt token amount to payback.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function payback(string calldata tokenId, uint amt, uint getId, uint setId) external payable {
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
CTokenInterface cTokenContract = CTokenInterface(cToken);
_amt = _amt == uint(-1) ? cTokenContract.borrowBalanceCurrent(address(this)) : _amt;
if (token == getAddressETH()) {
require(address(this).balance >= _amt, "not-enough-eth");
CETHInterface(cToken).repayBorrow.value(_amt)();
} else {
TokenInterface tokenContract = TokenInterface(token);
require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token");
tokenContract.approve(cToken, _amt);
require(cTokenContract.repayBorrow(_amt) == 0, "repay-failed.");
}
setUint(setId, _amt);
emit LogPayback(token, tokenId, cToken, _amt, getId, setId);
}
}
contract ExtraResolver is BasicResolver {
event LogClaimedComp(uint256 compAmt, uint256 setId);
event LogDepositCToken(
address indexed token,
string tokenId,
address cToken,
uint256 tokenAmt,
uint256 cTokenAmt,
uint256 getId,
uint256 setId
);
event LogWithdrawCToken(
address indexed token,
string tokenId,
address cToken,
uint256 tokenAmt,
uint256 cTokenAmt,
uint256 getId,
uint256 setId
);
event LogLiquidate(
address indexed borrower,
address indexed tokenToPay,
address indexed tokenInReturn,
uint256 tokenAmt,
uint256 getId,
uint256 setId
);
struct LiquidateData {
address tokenToPay;
address tokenInReturn;
address cTokenPay;
address cTokenColl;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param tokenId token id of the token to depositCToken.(For eg: DAI-A)
* @param amt token amount to depositCToken.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set ctoken amount at this ID in `InstaMemory` Contract.
*/
function depositCToken(string calldata tokenId, uint amt, uint getId, uint setId) external payable{
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
enterMarket(cToken);
CTokenInterface ctokenContract = CTokenInterface(cToken);
uint initialBal = ctokenContract.balanceOf(address(this));
if (token == getAddressETH()) {
_amt = _amt == uint(-1) ? address(this).balance : _amt;
CETHInterface(cToken).mint.value(_amt)();
} else {
TokenInterface tokenContract = TokenInterface(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
tokenContract.approve(cToken, _amt);
require(ctokenContract.mint(_amt) == 0, "deposit-ctoken-failed.");
}
uint finalBal = ctokenContract.balanceOf(address(this));
uint _cAmt = finalBal - initialBal;
setUint(setId, _cAmt);
emit LogDepositCToken(token, tokenId, cToken, _amt, _cAmt, getId, setId);
}
/**
* @dev Withdraw CETH/CERC20_Token using cToken Amt.
* @param tokenId token id of the token to withdraw CToken.(For eg: ETH-A)
* @param cTokenAmt ctoken amount to withdrawCToken.
* @param getId Get ctoken amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdrawCToken(string calldata tokenId, uint cTokenAmt, uint getId, uint setId) external payable {
uint _cAmt = getUint(getId, cTokenAmt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
CTokenInterface cTokenContract = CTokenInterface(cToken);
TokenInterface tokenContract = TokenInterface(token);
_cAmt = _cAmt == uint(-1) ? cTokenContract.balanceOf(address(this)) : _cAmt;
uint withdrawAmt;
{
uint initialBal = token != getAddressETH() ? tokenContract.balanceOf(address(this)) : address(this).balance;
require(cTokenContract.redeem(_cAmt) == 0, "redeem-failed");
uint finalBal = token != getAddressETH() ? tokenContract.balanceOf(address(this)) : address(this).balance;
withdrawAmt = sub(finalBal, initialBal);
}
setUint(setId, withdrawAmt);
emit LogWithdrawCToken(token, tokenId, cToken, withdrawAmt, _cAmt, getId, setId);
}
/**
* @dev Liquidate a position.
* @param borrower Borrower's Address.
* @param tokenIdToPay token id of the token to pay for liquidation.(For eg: ETH-A)
* @param tokenIdInReturn token id of the token to return for liquidation.(For eg: USDC-A)
* @param amt token amount to pay for liquidation.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function liquidate(
address borrower,
string calldata tokenIdToPay,
string calldata tokenIdInReturn,
uint amt,
uint getId,
uint setId
) external payable
{
uint _amt = getUint(getId, amt);
LiquidateData memory data;
(data.tokenToPay, data.cTokenPay) = InstaMappingV2(getMappingAddr()).getMapping(tokenIdToPay);
require(data.tokenToPay != address(0) && data.cTokenPay != address(0), "ctoken mapping not found");
(data.tokenInReturn, data.cTokenColl) = InstaMappingV2(getMappingAddr()).getMapping(tokenIdInReturn);
require(data.tokenInReturn != address(0) && data.cTokenColl != address(0), "ctoken mapping not found");
CTokenInterface cTokenContract = CTokenInterface(data.cTokenPay);
{
(,, uint shortfal) = ComptrollerInterface(getComptrollerAddress()).getAccountLiquidity(borrower);
require(shortfal != 0, "account-cannot-be-liquidated");
}
_amt = _amt == uint(-1) ? cTokenContract.borrowBalanceCurrent(borrower) : _amt;
if (data.tokenToPay == getAddressETH()) {
require(address(this).balance >= _amt, "not-enought-eth");
CETHInterface(data.cTokenPay).liquidateBorrow.value(_amt)(borrower, data.cTokenColl);
} else {
TokenInterface tokenContract = TokenInterface(data.tokenToPay);
require(tokenContract.balanceOf(address(this)) >= _amt, "not-enough-token");
tokenContract.approve(data.cTokenPay, _amt);
require(cTokenContract.liquidateBorrow(borrower, _amt, data.cTokenColl) == 0, "liquidate-failed");
}
setUint(setId, _amt);
emit LogLiquidate(
address(this),
data.tokenToPay,
data.tokenInReturn,
_amt,
getId,
setId
);
}
}
contract ConnectCompound is ExtraResolver {
string public name = "Compound-v1.4";
}
|
Borrow ETH/ERC20_Token. tokenId token id of the token to borrow.(For eg: DAI-A) amt token amount to borrow. getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./
|
function borrow(string calldata tokenId, uint amt, uint getId, uint setId) external payable {
uint _amt = getUint(getId, amt);
(address token, address cToken) = InstaMappingV2(getMappingAddr()).getMapping(tokenId);
require(token != address(0) && cToken != address(0), "ctoken mapping not found");
enterMarket(cToken);
require(CTokenInterface(cToken).borrow(_amt) == 0, "borrow-failed");
setUint(setId, _amt);
emit LogBorrow(token, tokenId, cToken, _amt, getId, setId);
}
| 1,571,109
|
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
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.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ERC20Receiver {
function onReceive(address _sender, address _from, uint256 _val) external returns (bool);
}
contract Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _addr) external onlyOwner {
owner = _addr;
}
}
pragma solidity ^0.5.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 {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 IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => address) internal _receivers;
uint256 internal _totalSupply;
string public constant name = "Totally normal tokenS";
string public constant symbol = "TONS";
uint256 public constant decimals = 18;
event SetReceiver(address _addr, address _receiver);
constructor() public {
_mint(msg.sender, 1000000 ether);
}
function receiverOf(address _addr) external view returns (address) {
return _receivers[_addr];
}
function setReceiver(address _for, address _addr) external onlyOwner {
emit SetReceiver(_for, _addr);
_receivers[_for] = _addr;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
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 {
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
address receiver = _receivers[recipient];
if (receiver != address(0)) {
require(ERC20Receiver(receiver).onReceive(msg.sender, sender, amount), "Reverted by receiver");
}
}
/** @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 Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
|
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
|
function _approve(address owner, address spender, uint256 value) internal {
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
| 14,057,550
|
./full_match/11155111/0x88aec82f14002a56014819f4e23a22eB32F528b1/sources/contracts/governance/Managed.sol
|
Sync protocol contract addresses from the Controller registry This function will cache all the contracts using the latest addresses Anyone can call the function whenever a Proxy contract change in the controller to ensure the protocol is using the latest version/
|
function syncAllContracts() external override {
_syncContract(CURATION);
_syncContract(EPOCH_MANAGER);
_syncContract(REWARDS_MANAGER);
_syncContract(STAKING);
_syncContract(GRAPH_TOKEN);
_syncContract(GRAPH_TOKEN_GATEWAY);
_syncContract(GNS);
}
| 3,839,096
|
pragma solidity 0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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 internal contractOwner;
constructor () internal {
if(contractOwner == address(0)){
contractOwner = msg.sender;
}
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
/**
* @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));
contractOwner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private paused = false;
/**
* @dev Modifier to allow actions only when the contract IS paused
@dev If is paused msg.value is send back
*/
modifier whenNotPaused() {
if(paused == true && msg.value > 0){
msg.sender.transfer(msg.value);
}
require(!paused);
_;
}
/**
* @dev Called by the owner to pause, triggers stopped state
*/
function triggerPause() onlyOwner external {
paused = !paused;
}
}
/// @title A contract for creating new champs and making withdrawals
contract ChampFactory is Pausable{
event NewChamp(uint256 champID, address owner);
using SafeMath for uint; //SafeMath for overflow prevention
/*
* Variables
*/
struct Champ {
uint256 id; //same as position in Champ[]
uint256 attackPower;
uint256 defencePower;
uint256 cooldownTime; //how long does it take to be ready attack again
uint256 readyTime; //if is smaller than block.timestamp champ is ready to fight
uint256 winCount;
uint256 lossCount;
uint256 position; //position in leaderboard. subtract 1 and you got position in leaderboard[]
uint256 price; //selling price
uint256 withdrawCooldown; //if you one of the 800 best champs and withdrawCooldown is less as block.timestamp then you get ETH reward
uint256 eq_sword;
uint256 eq_shield;
uint256 eq_helmet;
bool forSale; //is champ for sale?
}
struct AddressInfo {
uint256 withdrawal;
uint256 champsCount;
uint256 itemsCount;
string name;
}
//Item struct
struct Item {
uint8 itemType; // 1 - Sword | 2 - Shield | 3 - Helmet
uint8 itemRarity; // 1 - Common | 2 - Uncommon | 3 - Rare | 4 - Epic | 5 - Legendery | 6 - Forged
uint256 attackPower;
uint256 defencePower;
uint256 cooldownReduction;
uint256 price;
uint256 onChampId; //can not be used to decide if item is on champ, because champ's id can be 0, 'bool onChamp' solves it.
bool onChamp;
bool forSale; //is item for sale?
}
mapping (address => AddressInfo) public addressInfo;
mapping (uint256 => address) public champToOwner;
mapping (uint256 => address) public itemToOwner;
mapping (uint256 => string) public champToName;
Champ[] public champs;
Item[] public items;
uint256[] public leaderboard;
uint256 internal createChampFee = 5 finney;
uint256 internal lootboxFee = 5 finney;
uint256 internal pendingWithdrawal = 0;
uint256 private randNonce = 0; //being used in generating random numbers
uint256 public champsForSaleCount;
uint256 public itemsForSaleCount;
/*
* Modifiers
*/
/// @dev Checks if msg.sender is owner of champ
modifier onlyOwnerOfChamp(uint256 _champId) {
require(msg.sender == champToOwner[_champId]);
_;
}
/// @dev Checks if msg.sender is NOT owner of champ
modifier onlyNotOwnerOfChamp(uint256 _champId) {
require(msg.sender != champToOwner[_champId]);
_;
}
/// @notice Checks if amount was sent
modifier isPaid(uint256 _price){
require(msg.value >= _price);
_;
}
/// @notice People are allowed to withdraw only if min. balance (0.01 gwei) is reached
modifier contractMinBalanceReached(){
require( (address(this).balance).sub(pendingWithdrawal) > 1000000 );
_;
}
/// @notice Checks if withdraw cooldown passed
modifier isChampWithdrawReady(uint256 _id){
require(champs[_id].withdrawCooldown < block.timestamp);
_;
}
/// @notice Distribute input funds between contract owner and players
modifier distributeInput(address _affiliateAddress){
//contract owner
uint256 contractOwnerWithdrawal = (msg.value / 100) * 50; // 50%
addressInfo[contractOwner].withdrawal += contractOwnerWithdrawal;
pendingWithdrawal += contractOwnerWithdrawal;
//affiliate
//checks if _affiliateAddress is set & if affiliate address is not buying player
if(_affiliateAddress != address(0) && _affiliateAddress != msg.sender){
uint256 affiliateBonus = (msg.value / 100) * 25; //provision is 25%
addressInfo[_affiliateAddress].withdrawal += affiliateBonus;
pendingWithdrawal += affiliateBonus;
}
_;
}
/*
* View
*/
/// @notice Gets champs by address
/// @param _owner Owner address
function getChampsByOwner(address _owner) external view returns(uint256[]) {
uint256[] memory result = new uint256[](addressInfo[_owner].champsCount);
uint256 counter = 0;
for (uint256 i = 0; i < champs.length; i++) {
if (champToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
/// @notice Gets total champs count
function getChampsCount() external view returns(uint256){
return champs.length;
}
/// @notice Gets champ's reward in wei
function getChampReward(uint256 _position) public view returns(uint256) {
if(_position <= 800){
//percentageMultipier = 10,000
//maxReward = 2000 = .2% * percentageMultipier
//subtractPerPosition = 2 = .0002% * percentageMultipier
//2000 - (2 * (_position - 1))
uint256 rewardPercentage = uint256(2000).sub(2 * (_position - 1));
//available funds are all funds - already pending
uint256 availableWithdrawal = address(this).balance.sub(pendingWithdrawal);
//calculate reward for champ's position
//1000000 = percentageMultipier * 100
return availableWithdrawal / 1000000 * rewardPercentage;
}else{
return uint256(0);
}
}
/*
* Internal
*/
/// @notice Generates random modulus
/// @param _modulus Max random modulus
function randMod(uint256 _modulus) internal returns(uint256) {
randNonce++;
return uint256(keccak256(randNonce, blockhash(block.number - 1))) % _modulus;
}
/*
* External
*/
/// @notice Creates new champ
/// @param _affiliateAddress Affiliate address (optional)
function createChamp(address _affiliateAddress) external payable
whenNotPaused
isPaid(createChampFee)
distributeInput(_affiliateAddress)
{
/*
Champ memory champ = Champ({
id: 0,
attackPower: 2 + randMod(4),
defencePower: 1 + randMod(4),
cooldownTime: uint256(1 days) - uint256(randMod(9) * 1 hours),
readyTime: 0,
winCount: 0,
lossCount: 0,
position: leaderboard.length + 1, //Last place in leaderboard is new champ's position. Used in new champ struct bellow. +1 to avoid zero position.
price: 0,
withdrawCooldown: uint256(block.timestamp),
eq_sword: 0,
eq_shield: 0,
eq_helmet: 0,
forSale: false
});
*/
// This line bellow is about 30k gas cheaper than lines above. They are the same. Lines above are just more readable.
uint256 id = champs.push(Champ(0, 2 + randMod(4), 1 + randMod(4), uint256(1 days) - uint256(randMod(9) * 1 hours), 0, 0, 0, leaderboard.length + 1, 0, uint256(block.timestamp), 0,0,0, false)) - 1;
champs[id].id = id; //sets id in Champ struct
leaderboard.push(id); //push champ on the last place in leaderboard
champToOwner[id] = msg.sender; //sets owner of this champ - msg.sender
addressInfo[msg.sender].champsCount++;
emit NewChamp(id, msg.sender);
}
/// @notice Change "CreateChampFee". If ETH price will grow up it can expensive to create new champ.
/// @param _fee New "CreateChampFee"
/// @dev Only owner of contract can change "CreateChampFee"
function setCreateChampFee(uint256 _fee) external onlyOwner {
createChampFee = _fee;
}
/// @notice Change champ's name
function changeChampsName(uint _champId, string _name) external
onlyOwnerOfChamp(_champId){
champToName[_champId] = _name;
}
/// @notice Change players's name
function changePlayersName(string _name) external {
addressInfo[msg.sender].name = _name;
}
/// @notice Withdraw champ's reward
/// @param _id Champ id
/// @dev Move champ reward to pending withdrawal to his wallet.
function withdrawChamp(uint _id) external
onlyOwnerOfChamp(_id)
contractMinBalanceReached
isChampWithdrawReady(_id)
whenNotPaused {
Champ storage champ = champs[_id];
require(champ.position <= 800);
champ.withdrawCooldown = block.timestamp + 1 days; //one withdrawal 1 per day
uint256 withdrawal = getChampReward(champ.position);
addressInfo[msg.sender].withdrawal += withdrawal;
pendingWithdrawal += withdrawal;
}
/// @dev Send all pending funds of caller's address
function withdrawToAddress(address _address) external
whenNotPaused {
address playerAddress = _address;
if(playerAddress == address(0)){ playerAddress = msg.sender; }
uint256 share = addressInfo[playerAddress].withdrawal; //gets pending funds
require(share > 0); //is it more than 0?
//first sets players withdrawal pending to 0 and subtract amount from playerWithdrawals then transfer funds to avoid reentrancy
addressInfo[playerAddress].withdrawal = 0; //set player's withdrawal pendings to 0
pendingWithdrawal = pendingWithdrawal.sub(share); //subtract share from total pendings
playerAddress.transfer(share); //transfer
}
}
/// @title Moderates items and creates new ones
contract Items is ChampFactory {
event NewItem(uint256 itemID, address owner);
constructor () internal {
//item -> nothing
items.push(Item(0, 0, 0, 0, 0, 0, 0, false, false));
}
/*
* Modifiers
*/
/// @notice Checks if sender is owner of item
modifier onlyOwnerOfItem(uint256 _itemId) {
require(_itemId != 0);
require(msg.sender == itemToOwner[_itemId]);
_;
}
/// @notice Checks if sender is NOT owner of item
modifier onlyNotOwnerOfItem(uint256 _itemId) {
require(msg.sender != itemToOwner[_itemId]);
_;
}
/*
* View
*/
///@notice Check if champ has something on
///@param _type Sword, shield or helmet
function hasChampSomethingOn(uint _champId, uint8 _type) internal view returns(bool){
Champ storage champ = champs[_champId];
if(_type == 1){
return (champ.eq_sword == 0) ? false : true;
}
if(_type == 2){
return (champ.eq_shield == 0) ? false : true;
}
if(_type == 3){
return (champ.eq_helmet == 0) ? false : true;
}
}
/// @notice Gets items by address
/// @param _owner Owner address
function getItemsByOwner(address _owner) external view returns(uint256[]) {
uint256[] memory result = new uint256[](addressInfo[_owner].itemsCount);
uint256 counter = 0;
for (uint256 i = 0; i < items.length; i++) {
if (itemToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
/*
* Public
*/
///@notice Takes item off champ
function takeOffItem(uint _champId, uint8 _type) public
onlyOwnerOfChamp(_champId) {
uint256 itemId;
Champ storage champ = champs[_champId];
if(_type == 1){
itemId = champ.eq_sword; //Get item ID
if (itemId > 0) { //0 = nothing
champ.eq_sword = 0; //take off sword
}
}
if(_type == 2){
itemId = champ.eq_shield; //Get item ID
if(itemId > 0) {//0 = nothing
champ.eq_shield = 0; //take off shield
}
}
if(_type == 3){
itemId = champ.eq_helmet; //Get item ID
if(itemId > 0) { //0 = nothing
champ.eq_helmet = 0; //take off
}
}
if(itemId > 0){
items[itemId].onChamp = false; //item is free to use, is not on champ
}
}
/*
* External
*/
///@notice Puts item on champ
function putOn(uint256 _champId, uint256 _itemId) external
onlyOwnerOfChamp(_champId)
onlyOwnerOfItem(_itemId) {
Champ storage champ = champs[_champId];
Item storage item = items[_itemId];
//checks if items is on some other champ
if(item.onChamp){
takeOffItem(item.onChampId, item.itemType); //take off from champ
}
item.onChamp = true; //item is on champ
item.onChampId = _champId; //champ's id
//put on
if(item.itemType == 1){
//take off actual sword
if(champ.eq_sword > 0){
takeOffItem(champ.id, 1);
}
champ.eq_sword = _itemId; //put on sword
}
if(item.itemType == 2){
//take off actual shield
if(champ.eq_shield > 0){
takeOffItem(champ.id, 2);
}
champ.eq_shield = _itemId; //put on shield
}
if(item.itemType == 3){
//take off actual helmet
if(champ.eq_helmet > 0){
takeOffItem(champ.id, 3);
}
champ.eq_helmet = _itemId; //put on helmet
}
}
/// @notice Opens loot box and generates new item
function openLootbox(address _affiliateAddress) external payable
whenNotPaused
isPaid(lootboxFee)
distributeInput(_affiliateAddress) {
uint256 pointToCooldownReduction;
uint256 randNum = randMod(1001); //random number <= 1000
uint256 pointsToShare; //total points given
uint256 itemID;
//sets up item
Item memory item = Item({
itemType: uint8(uint256(randMod(3) + 1)), //generates item type - max num is 2 -> 0 + 1 SWORD | 1 + 1 SHIELD | 2 + 1 HELMET;
itemRarity: uint8(0),
attackPower: 0,
defencePower: 0,
cooldownReduction: 0,
price: 0,
onChampId: 0,
onChamp: false,
forSale: false
});
// Gets Rarity of item
// 45% common
// 27% uncommon
// 19% rare
// 7% epic
// 2% legendary
if(450 > randNum){
pointsToShare = 25 + randMod(9); //25 basic + random number max to 8
item.itemRarity = uint8(1);
}else if(720 > randNum){
pointsToShare = 42 + randMod(17); //42 basic + random number max to 16
item.itemRarity = uint8(2);
}else if(910 > randNum){
pointsToShare = 71 + randMod(25); //71 basic + random number max to 24
item.itemRarity = uint8(3);
}else if(980 > randNum){
pointsToShare = 119 + randMod(33); //119 basic + random number max to 32
item.itemRarity = uint8(4);
}else{
pointsToShare = 235 + randMod(41); //235 basic + random number max to 40
item.itemRarity = uint8(5);
}
//Gets type of item
if(item.itemType == uint8(1)){ //ITEM IS SWORDS
item.attackPower = pointsToShare / 10 * 7; //70% attackPower
pointsToShare -= item.attackPower; //points left;
item.defencePower = pointsToShare / 10 * randMod(6); //up to 15% defencePower
pointsToShare -= item.defencePower; //points left;
item.cooldownReduction = pointsToShare * uint256(1 minutes); //rest of points is cooldown reduction
item.itemType = uint8(1);
}
if(item.itemType == uint8(2)){ //ITEM IS SHIELD
item.defencePower = pointsToShare / 10 * 7; //70% defencePower
pointsToShare -= item.defencePower; //points left;
item.attackPower = pointsToShare / 10 * randMod(6); //up to 15% attackPowerPower
pointsToShare -= item.attackPower; //points left;
item.cooldownReduction = pointsToShare * uint256(1 minutes); //rest of points is cooldown reduction
item.itemType = uint8(2);
}
if(item.itemType == uint8(3)){ //ITEM IS HELMET
pointToCooldownReduction = pointsToShare / 10 * 7; //70% cooldown reduction
item.cooldownReduction = pointToCooldownReduction * uint256(1 minutes); //points to time
pointsToShare -= pointToCooldownReduction; //points left;
item.attackPower = pointsToShare / 10 * randMod(6); //up to 15% attackPower
pointsToShare -= item.attackPower; //points left;
item.defencePower = pointsToShare; //rest of points is defencePower
item.itemType = uint8(3);
}
itemID = items.push(item) - 1;
itemToOwner[itemID] = msg.sender; //sets owner of this item - msg.sender
addressInfo[msg.sender].itemsCount++; //every address has count of items
emit NewItem(itemID, msg.sender);
}
/// @notice Change "lootboxFee".
/// @param _fee New "lootboxFee"
/// @dev Only owner of contract can change "lootboxFee"
function setLootboxFee(uint _fee) external onlyOwner {
lootboxFee = _fee;
}
}
/// @title Moderates buying and selling items
contract ItemMarket is Items {
event TransferItem(address from, address to, uint256 itemID);
/*
* Modifiers
*/
///@notice Checks if item is for sale
modifier itemIsForSale(uint256 _id){
require(items[_id].forSale);
_;
}
///@notice Checks if item is NOT for sale
modifier itemIsNotForSale(uint256 _id){
require(items[_id].forSale == false);
_;
}
///@notice If item is for sale then cancel sale
modifier ifItemForSaleThenCancelSale(uint256 _itemID){
Item storage item = items[_itemID];
if(item.forSale){
_cancelItemSale(item);
}
_;
}
///@notice Distribute sale eth input
modifier distributeSaleInput(address _owner) {
uint256 contractOwnerCommision; //1%
uint256 playerShare; //99%
if(msg.value > 100){
contractOwnerCommision = (msg.value / 100);
playerShare = msg.value - contractOwnerCommision;
}else{
contractOwnerCommision = 0;
playerShare = msg.value;
}
addressInfo[_owner].withdrawal += playerShare;
addressInfo[contractOwner].withdrawal += contractOwnerCommision;
pendingWithdrawal += playerShare + contractOwnerCommision;
_;
}
/*
* View
*/
function getItemsForSale() view external returns(uint256[]){
uint256[] memory result = new uint256[](itemsForSaleCount);
if(itemsForSaleCount > 0){
uint256 counter = 0;
for (uint256 i = 0; i < items.length; i++) {
if (items[i].forSale == true) {
result[counter]=i;
counter++;
}
}
}
return result;
}
/*
* Private
*/
///@notice Cancel sale. Should not be called without checking if item is really for sale.
function _cancelItemSale(Item storage item) private {
//No need to overwrite item's price
item.forSale = false;
itemsForSaleCount--;
}
/*
* Internal
*/
/// @notice Transfer item
function transferItem(address _from, address _to, uint256 _itemID) internal
ifItemForSaleThenCancelSale(_itemID) {
Item storage item = items[_itemID];
//take off
if(item.onChamp && _to != champToOwner[item.onChampId]){
takeOffItem(item.onChampId, item.itemType);
}
addressInfo[_to].itemsCount++;
addressInfo[_from].itemsCount--;
itemToOwner[_itemID] = _to;
emit TransferItem(_from, _to, _itemID);
}
/*
* Public
*/
/// @notice Calls transfer item
/// @notice Address _from is msg.sender. Cannot be used is market, bc msg.sender is buyer
function giveItem(address _to, uint256 _itemID) public
onlyOwnerOfItem(_itemID) {
transferItem(msg.sender, _to, _itemID);
}
/// @notice Calcels item's sale
function cancelItemSale(uint256 _id) public
itemIsForSale(_id)
onlyOwnerOfItem(_id){
Item storage item = items[_id];
_cancelItemSale(item);
}
/*
* External
*/
/// @notice Sets item for sale
function setItemForSale(uint256 _id, uint256 _price) external
onlyOwnerOfItem(_id)
itemIsNotForSale(_id) {
Item storage item = items[_id];
item.forSale = true;
item.price = _price;
itemsForSaleCount++;
}
/// @notice Buys item
function buyItem(uint256 _id) external payable
whenNotPaused
onlyNotOwnerOfItem(_id)
itemIsForSale(_id)
isPaid(items[_id].price)
distributeSaleInput(itemToOwner[_id])
{
transferItem(itemToOwner[_id], msg.sender, _id);
}
}
/// @title Manages forging
contract ItemForge is ItemMarket {
event Forge(uint256 forgedItemID);
///@notice Forge items together
function forgeItems(uint256 _parentItemID, uint256 _childItemID) external
onlyOwnerOfItem(_parentItemID)
onlyOwnerOfItem(_childItemID)
ifItemForSaleThenCancelSale(_parentItemID)
ifItemForSaleThenCancelSale(_childItemID) {
//checks if items are not the same
require(_parentItemID != _childItemID);
Item storage parentItem = items[_parentItemID];
Item storage childItem = items[_childItemID];
//take child item off, because child item will be burned
if(childItem.onChamp){
takeOffItem(childItem.onChampId, childItem.itemType);
}
//update parent item
parentItem.attackPower = (parentItem.attackPower > childItem.attackPower) ? parentItem.attackPower : childItem.attackPower;
parentItem.defencePower = (parentItem.defencePower > childItem.defencePower) ? parentItem.defencePower : childItem.defencePower;
parentItem.cooldownReduction = (parentItem.cooldownReduction > childItem.cooldownReduction) ? parentItem.cooldownReduction : childItem.cooldownReduction;
parentItem.itemRarity = uint8(6);
//burn child item
transferItem(msg.sender, address(0), _childItemID);
emit Forge(_parentItemID);
}
}
/// @title Manages attacks in game
contract ChampAttack is ItemForge {
event Attack(uint256 winnerChampID, uint256 defeatedChampID, bool didAttackerWin);
/*
* Modifiers
*/
/// @notice Is champ ready to fight again?
modifier isChampReady(uint256 _champId) {
require (champs[_champId].readyTime <= block.timestamp);
_;
}
/// @notice Prevents from self-attack
modifier notSelfAttack(uint256 _champId, uint256 _targetId) {
require(_champId != _targetId);
_;
}
/// @notice Checks if champ does exist
modifier targetExists(uint256 _targetId){
require(champToOwner[_targetId] != address(0));
_;
}
/*
* View
*/
/// @notice Gets champ's attack power, defence power and cooldown reduction with items on
function getChampStats(uint256 _champId) public view returns(uint256,uint256,uint256){
Champ storage champ = champs[_champId];
Item storage sword = items[champ.eq_sword];
Item storage shield = items[champ.eq_shield];
Item storage helmet = items[champ.eq_helmet];
//AP
uint256 totalAttackPower = champ.attackPower + sword.attackPower + shield.attackPower + helmet.attackPower; //Gets champs AP
//DP
uint256 totalDefencePower = champ.defencePower + sword.defencePower + shield.defencePower + helmet.defencePower; //Gets champs DP
//CR
uint256 totalCooldownReduction = sword.cooldownReduction + shield.cooldownReduction + helmet.cooldownReduction; //Gets CR
return (totalAttackPower, totalDefencePower, totalCooldownReduction);
}
/*
* Pure
*/
/// @notice Subtracts ability points. Helps to not cross minimal attack ability points -> 2
/// @param _playerAttackPoints Actual player's attack points
/// @param _x Amount to subtract
function subAttack(uint256 _playerAttackPoints, uint256 _x) internal pure returns (uint256) {
return (_playerAttackPoints <= _x + 2) ? 2 : _playerAttackPoints - _x;
}
/// @notice Subtracts ability points. Helps to not cross minimal defence ability points -> 1
/// @param _playerDefencePoints Actual player's defence points
/// @param _x Amount to subtract
function subDefence(uint256 _playerDefencePoints, uint256 _x) internal pure returns (uint256) {
return (_playerDefencePoints <= _x) ? 1 : _playerDefencePoints - _x;
}
/*
* Private
*/
/// @dev Is called from from Attack function after the winner is already chosen
/// @dev Updates abilities, champ's stats and swaps positions
function _attackCompleted(Champ storage _winnerChamp, Champ storage _defeatedChamp, uint256 _pointsGiven, uint256 _pointsToAttackPower) private {
/*
* Updates abilities after fight
*/
//winner abilities update
_winnerChamp.attackPower += _pointsToAttackPower; //increase attack power
_winnerChamp.defencePower += _pointsGiven - _pointsToAttackPower; //max point that was given - already given to AP
//defeated champ's abilities update
//checks for not cross minimal AP & DP points
_defeatedChamp.attackPower = subAttack(_defeatedChamp.attackPower, _pointsToAttackPower); //decrease attack power
_defeatedChamp.defencePower = subDefence(_defeatedChamp.defencePower, _pointsGiven - _pointsToAttackPower); // decrease defence power
/*
* Update champs' wins and losses
*/
_winnerChamp.winCount++;
_defeatedChamp.lossCount++;
/*
* Swap positions
*/
if(_winnerChamp.position > _defeatedChamp.position) { //require loser to has better (lower) postion than attacker
uint256 winnerPosition = _winnerChamp.position;
uint256 loserPosition = _defeatedChamp.position;
_defeatedChamp.position = winnerPosition;
_winnerChamp.position = loserPosition;
//position in champ struct is always one point bigger than in leaderboard array
leaderboard[winnerPosition - 1] = _defeatedChamp.id;
leaderboard[loserPosition - 1] = _winnerChamp.id;
}
}
/// @dev Gets pointsGiven and pointsToAttackPower
function _getPoints(uint256 _pointsGiven) private returns (uint256 pointsGiven, uint256 pointsToAttackPower){
return (_pointsGiven, randMod(_pointsGiven+1));
}
/*
* External
*/
/// @notice Attack function
/// @param _champId Attacker champ
/// @param _targetId Target champ
function attack(uint256 _champId, uint256 _targetId) external
onlyOwnerOfChamp(_champId)
isChampReady(_champId)
notSelfAttack(_champId, _targetId)
targetExists(_targetId) {
Champ storage myChamp = champs[_champId];
Champ storage enemyChamp = champs[_targetId];
uint256 pointsGiven; //total points that will be divided between AP and DP
uint256 pointsToAttackPower; //part of points that will be added to attack power, the rest of points go to defence power
uint256 myChampAttackPower;
uint256 enemyChampDefencePower;
uint256 myChampCooldownReduction;
(myChampAttackPower,,myChampCooldownReduction) = getChampStats(_champId);
(,enemyChampDefencePower,) = getChampStats(_targetId);
//if attacker's AP is more than target's DP then attacker wins
if (myChampAttackPower > enemyChampDefencePower) {
//this should demotivate players from farming on way weaker champs than they are
//the bigger difference between AP & DP is, the reward is smaller
if(myChampAttackPower - enemyChampDefencePower < 5){
//big experience - 3 ability points
(pointsGiven, pointsToAttackPower) = _getPoints(3);
}else if(myChampAttackPower - enemyChampDefencePower < 10){
//medium experience - 2 ability points
(pointsGiven, pointsToAttackPower) = _getPoints(2);
}else{
//small experience - 1 ability point to random ability (attack power or defence power)
(pointsGiven, pointsToAttackPower) = _getPoints(1);
}
_attackCompleted(myChamp, enemyChamp, pointsGiven, pointsToAttackPower);
emit Attack(myChamp.id, enemyChamp.id, true);
} else {
//1 ability point to random ability (attack power or defence power)
(pointsGiven, pointsToAttackPower) = _getPoints(1);
_attackCompleted(enemyChamp, myChamp, pointsGiven, pointsToAttackPower);
emit Attack(enemyChamp.id, myChamp.id, false);
}
//Trigger cooldown for attacker
myChamp.readyTime = uint256(block.timestamp + myChamp.cooldownTime - myChampCooldownReduction);
}
}
/// @title Moderates buying and selling champs
contract ChampMarket is ChampAttack {
event TransferChamp(address from, address to, uint256 champID);
/*
* Modifiers
*/
///@notice Require champ to be sale
modifier champIsForSale(uint256 _id){
require(champs[_id].forSale);
_;
}
///@notice Require champ NOT to be for sale
modifier champIsNotForSale(uint256 _id){
require(champs[_id].forSale == false);
_;
}
///@notice If champ is for sale then cancel sale
modifier ifChampForSaleThenCancelSale(uint256 _champID){
Champ storage champ = champs[_champID];
if(champ.forSale){
_cancelChampSale(champ);
}
_;
}
/*
* View
*/
///@notice Gets all champs for sale
function getChampsForSale() view external returns(uint256[]){
uint256[] memory result = new uint256[](champsForSaleCount);
if(champsForSaleCount > 0){
uint256 counter = 0;
for (uint256 i = 0; i < champs.length; i++) {
if (champs[i].forSale == true) {
result[counter]=i;
counter++;
}
}
}
return result;
}
/*
* Private
*/
///@dev Cancel sale. Should not be called without checking if champ is really for sale.
function _cancelChampSale(Champ storage champ) private {
//cancel champ's sale
//no need waste gas to overwrite his price.
champ.forSale = false;
champsForSaleCount--;
}
/*
* Internal
*/
/// @notice Transfer champ
function transferChamp(address _from, address _to, uint256 _champId) internal ifChampForSaleThenCancelSale(_champId){
Champ storage champ = champs[_champId];
//transfer champ
addressInfo[_to].champsCount++;
addressInfo[_from].champsCount--;
champToOwner[_champId] = _to;
//transfer items
if(champ.eq_sword != 0) { transferItem(_from, _to, champ.eq_sword); }
if(champ.eq_shield != 0) { transferItem(_from, _to, champ.eq_shield); }
if(champ.eq_helmet != 0) { transferItem(_from, _to, champ.eq_helmet); }
emit TransferChamp(_from, _to, _champId);
}
/*
* Public
*/
/// @notice Champ is no more for sale
function cancelChampSale(uint256 _id) public
champIsForSale(_id)
onlyOwnerOfChamp(_id) {
Champ storage champ = champs[_id];
_cancelChampSale(champ);
}
/*
* External
*/
/// @notice Gift champ
/// @dev Address _from is msg.sender
function giveChamp(address _to, uint256 _champId) external
onlyOwnerOfChamp(_champId) {
transferChamp(msg.sender, _to, _champId);
}
/// @notice Sets champ for sale
function setChampForSale(uint256 _id, uint256 _price) external
onlyOwnerOfChamp(_id)
champIsNotForSale(_id) {
Champ storage champ = champs[_id];
champ.forSale = true;
champ.price = _price;
champsForSaleCount++;
}
/// @notice Buys champ
function buyChamp(uint256 _id) external payable
whenNotPaused
onlyNotOwnerOfChamp(_id)
champIsForSale(_id)
isPaid(champs[_id].price)
distributeSaleInput(champToOwner[_id]) {
transferChamp(champToOwner[_id], msg.sender, _id);
}
}
/// @title Only used for deploying all contracts
contract MyCryptoChampCore is ChampMarket {
/*
© Copyright 2018 - Patrik Mojzis
Redistributing and modifying is prohibited.
https://mycryptochamp.io/
What is MyCryptoChamp?
- Blockchain game about upgrading champs by fighting, getting better items,
trading them and the best 800 champs are daily rewarded by real Ether.
Feel free to ask any questions
hello@mycryptochamp.io
*/
}
|
Public/ Calls transfer item Address _from is msg.sender. Cannot be used is market, bc msg.sender is buyer
|
function giveItem(address _to, uint256 _itemID) public
onlyOwnerOfItem(_itemID) {
transferItem(msg.sender, _to, _itemID);
}
| 6,456,943
|
./full_match/44787/0x8ac2602c5CafA224f4ab918F2ee520e1735a2af3/sources/contracts/vehicleController.sol
|
Returns the current vehicle ID. Can only be done by the fleet owner./
|
function returnCurrentId() public view onlyFleetOwner returns (uint256) {
return _vehicleCounter.current();
}
| 13,280,356
|
/*
Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity >= 0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "./interfaces/ISTokens.sol";
import "./interfaces/IUTokens.sol";
import "./interfaces/IHolder.sol";
import "./libraries/FullMath.sol";
contract STokens is ERC20Upgradeable, ISTokens, PausableUpgradeable, AccessControlUpgradeable {
using SafeMathUpgradeable for uint256;
using FullMath for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// constants defining access control ROLES
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// variables pertaining to holder logic for whitelisted addresses & StakeLP
// deposit contract address for STokens in a DeFi product
EnumerableSetUpgradeable.AddressSet private _whitelistedAddresses;
mapping(address => address) private _holderContractAddress;
// LP Token contract address which might be different from whitelisted contract
mapping(address => address) private _lpContractAddress;
// last timestamp when the holder reward calculation was performed for updating reward pool
mapping(address => uint256) private _lastHolderRewardTimestamp;
// variables capturing data of other contracts in the product
address private _liquidStakingContract;
IUTokens private _uTokens;
// variables pertaining to moving reward rate logic
uint256[] private _rewardRate;
uint256[] private _lastMovingRewardTimestamp;
uint256 private _valueDivisor;
mapping(address => uint256) private _lastUserRewardTimestamp;
/**
* @dev Constructor for initializing the SToken contract.
* @param uaddress - address of the UToken contract.
* @param pauserAddress - address of the pauser admin.
* @param rewardRate - set to rewardRate * 10^-5
* @param valueDivisor - valueDivisor set to 10^9.
*/
function initialize(address uaddress, address pauserAddress, uint256 rewardRate, uint256 valueDivisor) public virtual initializer {
__ERC20_init("pSTAKE Staked ATOM", "stkATOM");
__AccessControl_init();
__Pausable_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, pauserAddress);
setUTokensContract(uaddress);
_valueDivisor = valueDivisor;
require(rewardRate <= _valueDivisor.mul(100), "ST1");
_rewardRate.push(rewardRate);
_lastMovingRewardTimestamp.push(block.timestamp);
_setupDecimals(6);
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param lpContractAddress: contract address
*/
function isContractWhitelisted(address lpContractAddress) public view virtual override returns (bool result, address holderAddress){
// Get the time in number of blocks
address _lpContractAddressLocal;
// valueDivisor = _valueDivisor;
uint256 _whitelistedAddressesLength = _whitelistedAddresses.length();
for (uint256 i=0; i<_whitelistedAddressesLength; i=i.add(1)) {
//get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed
_lpContractAddressLocal = _lpContractAddress[_whitelistedAddresses.at(i)];
if(_lpContractAddressLocal == lpContractAddress) {
result = true;
holderAddress = _holderContractAddress[_whitelistedAddresses.at(i)];
break;
}
}
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param whitelistedAddress: contract address
*/
function getHolderData(address whitelistedAddress) public view virtual override returns (address holderAddress, address lpAddress, uint256 lastHolderRewardTimestamp){
// Get the time in number of blocks
holderAddress = _holderContractAddress[whitelistedAddress];
lpAddress = _lpContractAddress[whitelistedAddress];
lastHolderRewardTimestamp = _lastHolderRewardTimestamp[whitelistedAddress];
}
/*
* @dev set reward rate called by admin
* @param rewardRate: reward rate
*
*
* Requirements:
*
* - `rate` cannot be less than or equal to zero.
*
*/
function setRewardRate(uint256 rewardRate) public virtual override returns (bool success) {
// range checks for rewardRate. Since rewardRate cannot be more than 100%, the max cap
// is _valueDivisor * 100, which then brings the fees to 100 (percentage)
require(rewardRate <= _valueDivisor.mul(100), "ST1");
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST2");
_rewardRate.push(rewardRate);
_lastMovingRewardTimestamp.push(block.timestamp);
return true;
}
/**
* @dev get reward rate and value divisor
*/
function getRewardRate() public view virtual returns (uint256[] memory rewardRate, uint256 valueDivisor) {
rewardRate = _rewardRate;
valueDivisor = _valueDivisor;
}
/**
* @dev get rewards till timestamp
* @param to: account address
*/
function getLastUserRewardTimestamp(address to) public view virtual returns (uint256 lastUserRewardTimestamp) {
lastUserRewardTimestamp = _lastUserRewardTimestamp[to];
}
/**
* @dev Mint new stokens for the provided 'address' and 'tokens'
* @param to: account address, tokens: number of tokens
*
* Emits a {MintTokens} event with 'to' set to address and 'tokens' set to amount of tokens.
*
* Requirements:
*
* - `amount` cannot be less than zero.
*
*/
function mint(address to, uint256 tokens) public virtual override returns (bool) {
require(tx.origin == to && _msgSender() == _liquidStakingContract, "ST3");
_mint(to, tokens);
return true;
}
/*
* @dev Burn stokens for the provided 'address' and 'tokens'
* @param to: account address, tokens: number of tokens
*
* Emits a {BurnTokens} event with 'to' set to address and 'tokens' set to amount of tokens.
*
* Requirements:
*
* - `amount` cannot be less than zero.
*
*/
function burn(address from, uint256 tokens) public virtual override returns (bool) {
require(tx.origin == from && _msgSender() == _liquidStakingContract, "ST4");
_burn(from, tokens);
return true;
}
/**
* @dev Calculate pending rewards from the provided 'principal' & 'lastRewardTimestamp'. The rate is the moving reward rate.
* @param principal: principal amount
* @param lastRewardTimestamp: timestamp of last reward calculation performed
*/
function _calculatePendingRewards(uint256 principal, uint256 lastRewardTimestamp) internal view returns (uint256 pendingRewards){
uint256 _index;
uint256 _rewardBlocks;
uint256 _simpleInterestOfInterval;
uint256 _temp;
// return 0 if principal or timeperiod is zero
if(principal == 0 || block.timestamp.sub(lastRewardTimestamp) == 0) return 0;
// calculate rewards for each interval period between rewardRate changes
uint256 _lastMovingRewardLength = _lastMovingRewardTimestamp.length.sub(1);
for(_index = _lastMovingRewardLength; _index >= 0;){
// logic applies for all indexes of array except last index
if(_index < _lastMovingRewardTimestamp.length.sub(1)) {
if(_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) {
_rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)]).sub(_lastMovingRewardTimestamp[_index]);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor);
pendingRewards = pendingRewards.add(_simpleInterestOfInterval);
}
else {
_rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)]).sub(lastRewardTimestamp);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor);
pendingRewards = pendingRewards.add(_simpleInterestOfInterval);
break;
}
}
// logic applies only for the last index of array
else {
if(_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) {
_rewardBlocks = (block.timestamp).sub(_lastMovingRewardTimestamp[_index]);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor);
pendingRewards = pendingRewards.add(_simpleInterestOfInterval);
}
else {
_rewardBlocks = (block.timestamp).sub(lastRewardTimestamp);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(_rewardBlocks, _valueDivisor);
pendingRewards = pendingRewards.add(_simpleInterestOfInterval);
break;
}
}
if(_index == 0) break;
else {
_index = _index.sub(1);
}
}
return pendingRewards;
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param to: account address
*/
function calculatePendingRewards(address to) public view virtual override returns (uint256 pendingRewards){
// Get the time in number of blocks
uint256 _lastRewardTimestamp = _lastUserRewardTimestamp[to];
// Get the balance of the account
uint256 _balance = balanceOf(to);
// calculate pending rewards using _calculatePendingRewards
pendingRewards = _calculatePendingRewards(_balance, _lastRewardTimestamp);
return pendingRewards;
}
/**
* @dev Calculate rewards for the provided 'address'
* @param to: account address
*/
function _calculateRewards(address to) internal returns (uint256){
// Calculate the rewards pending
uint256 _reward = calculatePendingRewards(to);
// Set the new stakedBlock to the current,
// as per Checks-Effects-Interactions pattern
_lastUserRewardTimestamp[to] = block.timestamp;
// mint uTokens only if reward is greater than zero
if(_reward>0) {
// Mint new uTokens and send to the callers account
_uTokens.mint(to, _reward);
emit CalculateRewards(to, _reward, block.timestamp);
}
return _reward;
}
/**
* @dev Calculate rewards for the provided 'address'
* @param to: account address
*
* Emits a {TriggeredCalculateRewards} event with 'to' set to address, 'reward' set to amount of tokens and 'timestamp'
*
*/
function calculateRewards(address to) public virtual override whenNotPaused returns (bool success) {
require(to == _msgSender(), "ST5");
uint256 reward = _calculateRewards(to);
emit TriggeredCalculateRewards(to, reward, block.timestamp);
return true;
}
/**
* @dev Calculate rewards for the provided 'holder address'
* @param to: address
* @param from: address
* @param amount: token amount
*/
function _calculateHolderRewards(address to, address from, uint256 amount) internal returns (uint256){
// holderContract and lpContract (lp token contract) need to be validated together because
// it might not be practical to setup holder to collect reward pool but not StakeLP to distribute reward
// since the reward distribution calculation starts the minute reward pool is created
require(_whitelistedAddresses.contains(to) && _holderContractAddress[to] != address(0) && _lpContractAddress[to] != address(0), "ST6");
uint256 _sTokenSupply = IHolder(_holderContractAddress[to]).getSTokenSupply(to, from, amount);
// calculate the reward applying the moving reward rate
uint256 _newRewards = _calculatePendingRewards(_sTokenSupply, _lastHolderRewardTimestamp[to]);
// update the last timestamp of reward pool to the current time as per Checks-Effects-Interactions pattern
_lastHolderRewardTimestamp[to] = block.timestamp;
// Mint new uTokens and send to the holder contract account as updated reward pool
if(_newRewards > 0) {
_uTokens.mint(_holderContractAddress[to], _newRewards);
emit CalculateHolderRewards(_holderContractAddress[to], _newRewards, block.timestamp);
}
return _newRewards;
}
/**
* @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.
*
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
require(!paused(), "ST7");
super._beforeTokenTransfer(from, to, amount);
if(from == address(0)){
if(!_whitelistedAddresses.contains(to)){
_calculateRewards(to);
}
else {
_calculateHolderRewards(to, from, amount);
}
}
if(from != address(0) && !_whitelistedAddresses.contains(from)){
if(to == address(0)){
_calculateRewards(from);
}
if(to != address(0) && !_whitelistedAddresses.contains(to)){
_calculateRewards(from);
_calculateRewards(to);
}
if(to != address(0) && _whitelistedAddresses.contains(to)){
_calculateRewards(from);
_calculateHolderRewards(to, from, amount);
}
}
if(from != address(0) && _whitelistedAddresses.contains(from)){
if(to == address(0)){
_calculateHolderRewards(from, to, amount);
}
if(to != address(0) && !_whitelistedAddresses.contains(to)){
_calculateHolderRewards(from, to, amount);
_calculateRewards(to);
}
if(to != address(0) && _whitelistedAddresses.contains(to)){
_calculateHolderRewards(from, address(0), amount);
_calculateHolderRewards(to, address(0), amount);
}
}
}
/*
* @dev Set 'whitelisted address', performed by admin only
* @param whitelistedAddress: contract address of the whitelisted party
* @param holderContractAddress: holder contract address
* @param lpContractAddress: LP token contract address
*
* Emits a {setWhitelistedAddress} event
*
*/
function setWhitelistedAddress(address whitelistedAddress, address holderContractAddress, address lpContractAddress) public virtual returns (bool success){
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST8");
// lpTokenERC20ContractAddress or sTokenReserveContractAddress can be address(0) but not whitelistedAddress
require(whitelistedAddress != address(0), "ST9");
// add the whitelistedAddress if it isn't already available
if(!_whitelistedAddresses.contains(whitelistedAddress)) _whitelistedAddresses.add(whitelistedAddress);
// add the contract addresses to holder mapping variable
_holderContractAddress[whitelistedAddress] = holderContractAddress;
_lpContractAddress[whitelistedAddress] = lpContractAddress;
emit SetWhitelistedAddress(whitelistedAddress, holderContractAddress, lpContractAddress, block.timestamp);
success = true;
return success;
}
/*
* @dev remove 'whitelisted address', performed by admin only
* @param whitelistedAddress: contract address of the whitelisted party
*
* Emits a {RemoveWhitelistedAddress} event
*
*/
function removeWhitelistedAddress(address whitelistedAddress) public virtual returns (bool success){
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST10");
require(whitelistedAddress != address(0), "ST11");
// remove whitelistedAddress from the list
_whitelistedAddresses.remove(whitelistedAddress);
address _holderContractAddressLocal = _holderContractAddress[whitelistedAddress];
address _lpContractAddressLocal = _lpContractAddress[whitelistedAddress];
// delete holder contract values
delete _holderContractAddress[whitelistedAddress];
delete _lpContractAddress[whitelistedAddress];
emit RemoveWhitelistedAddress(whitelistedAddress, _holderContractAddressLocal, _lpContractAddressLocal, block.timestamp);
success = true;
return success;
}
/*
* @dev Set 'contract address', called from constructor
* @param uTokenContract: utoken contract address
*
* Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address.
*
*/
function setUTokensContract(address uTokenContract) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST12");
_uTokens = IUTokens(uTokenContract);
emit SetUTokensContract(uTokenContract);
}
/*
* @dev Set 'contract address', called from constructor
* @param liquidStakingContract: liquidStaking contract address
*
* Emits a {SetLiquidStakingContract} event with '_contract' set to the liquidStaking contract address.
*
*/
function setLiquidStakingContract(address liquidStakingContract) public virtual override{
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST13");
_liquidStakingContract = liquidStakingContract;
emit SetLiquidStakingContract(liquidStakingContract);
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() public virtual returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "ST14");
_pause();
return true;
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() public virtual returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "ST15");
_unpause();
return true;
}
}
|
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./
|
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
require(!paused(), "ST7");
super._beforeTokenTransfer(from, to, amount);
if(from == address(0)){
if(!_whitelistedAddresses.contains(to)){
_calculateRewards(to);
}
else {
_calculateHolderRewards(to, from, amount);
}
}
if(from != address(0) && !_whitelistedAddresses.contains(from)){
if(to == address(0)){
_calculateRewards(from);
}
if(to != address(0) && !_whitelistedAddresses.contains(to)){
_calculateRewards(from);
_calculateRewards(to);
}
if(to != address(0) && _whitelistedAddresses.contains(to)){
_calculateRewards(from);
_calculateHolderRewards(to, from, amount);
}
}
if(from != address(0) && _whitelistedAddresses.contains(from)){
if(to == address(0)){
_calculateHolderRewards(from, to, amount);
}
if(to != address(0) && !_whitelistedAddresses.contains(to)){
_calculateHolderRewards(from, to, amount);
_calculateRewards(to);
}
if(to != address(0) && _whitelistedAddresses.contains(to)){
_calculateHolderRewards(from, address(0), amount);
_calculateHolderRewards(to, address(0), amount);
}
}
}
| 947,075
|
./partial_match/4/0x7f1BabC962221C78b1412Cea08D191A7Ed391Bd3/sources/Lemniscate.sol
|
-- APPLICATION ENTRY POINTS --/ Converts all incoming wrappedBTC to tokens for the caller, and passes down the referral addy (if any)/
|
function buy(address _referredBy, uint256 amount) public returns (uint256) {
ERC20 Wbtc = ERC20(tokenAddress);
Wbtc.transferFrom(msg.sender, address(this), amount);
purchaseTokens(amount, _referredBy, false); }
| 8,503,713
|
/**
*Submitted for verification at Etherscan.io on 2020-02-11
*/
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/apps-agent/contracts/standards/ERC1271.sol
pragma solidity 0.4.24;
// ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md
// Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified
// Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728
contract ERC1271 {
bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector
bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated
bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000;
/**
* @dev Function must be implemented by deriving contract
* @param _hash Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4);
function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) {
return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE;
}
}
contract ERC1271Bytes is ERC1271 {
/**
* @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
* @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) {
return isValidSignature(keccak256(_data), _signature);
}
}
// File: @aragon/apps-agent/contracts/SignatureValidator.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol
// This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442
library SignatureValidator {
enum SignatureMode {
Invalid, // 0x00
EIP712, // 0x01
EthSign, // 0x02
ERC1271, // 0x03
NMode // 0x04, to check if mode is specified, leave at the end
}
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b;
uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000;
string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE";
/// @dev Validates that a hash was signed by a specified signer.
/// @param hash Hash which was signed.
/// @param signer Address of the signer.
/// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}.
/// @return Returns whether signature is from a specified user.
function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) {
if (signature.length == 0) {
return false;
}
uint8 modeByte = uint8(signature[0]);
if (modeByte >= uint8(SignatureMode.NMode)) {
return false;
}
SignatureMode mode = SignatureMode(modeByte);
if (mode == SignatureMode.EIP712) {
return ecVerify(hash, signer, signature);
} else if (mode == SignatureMode.EthSign) {
return ecVerify(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
signer,
signature
);
} else if (mode == SignatureMode.ERC1271) {
// Pop the mode byte before sending it down the validation chain
return safeIsValidSignature(signer, hash, popFirstByte(signature));
} else {
return false;
}
}
function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) {
(bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature);
if (badSig) {
return false;
}
return signer == ecrecover(hash, v, r, s);
}
function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) {
if (signature.length != 66) {
badSig = true;
return;
}
v = uint8(signature[65]);
assembly {
r := mload(add(signature, 33))
s := mload(add(signature, 65))
}
// Allow signature version to be 0 or 1
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
badSig = true;
}
}
function popFirstByte(bytes memory input) private pure returns (bytes memory output) {
uint256 inputLength = input.length;
require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE);
output = new bytes(inputLength - 1);
if (output.length == 0) {
return output;
}
uint256 inputPointer;
uint256 outputPointer;
assembly {
inputPointer := add(input, 0x21)
outputPointer := add(output, 0x20)
}
memcpy(outputPointer, inputPointer, output.length);
}
function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) {
bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature);
bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS);
return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE;
}
function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) {
uint256 gasLeft = gasleft();
uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft;
bool ok;
assembly {
ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0)
}
if (!ok) {
return;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return;
}
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
ret := mload(ptr) // read data at ptr and set it to be returned
}
return ret;
}
// From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol
function memcpy(uint256 dest, uint256 src, uint256 len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
// File: @aragon/apps-agent/contracts/standards/IERC165.sol
pragma solidity 0.4.24;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
}
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: @aragon/os/contracts/common/DepositableStorage.sol
pragma solidity 0.4.24;
contract DepositableStorage {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.depositableStorage.depositable")
bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea;
function isDepositable() public view returns (bool) {
return DEPOSITABLE_POSITION.getStorageBool();
}
function setDepositable(bool _depositable) internal {
DEPOSITABLE_POSITION.setStorageBool(_depositable);
}
}
// File: @aragon/apps-vault/contracts/Vault.sol
pragma solidity 0.4.24;
contract Vault is EtherTokenConstant, AragonApp, DepositableStorage {
using SafeERC20 for ERC20;
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO";
string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE";
string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO";
string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO";
string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED";
string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED";
event VaultTransfer(address indexed token, address indexed to, uint256 amount);
event VaultDeposit(address indexed token, address indexed sender, uint256 amount);
/**
* @dev On a normal send() or transfer() this fallback is never executed as it will be
* intercepted by the Proxy (see aragonOS#281)
*/
function () external payable isInitialized {
require(msg.data.length == 0, ERROR_DATA_NON_ZERO);
_deposit(ETH, msg.value);
}
/**
* @notice Initialize Vault app
* @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work
*/
function initialize() external onlyInit {
initialized();
setDepositable(true);
}
/**
* @notice Deposit `_value` `_token` to the vault
* @param _token Address of the token being transferred
* @param _value Amount of tokens being transferred
*/
function deposit(address _token, uint256 _value) external payable isInitialized {
_deposit(_token, _value);
}
/**
* @notice Transfer `_value` `_token` from the Vault to `_to`
* @param _token Address of the token being transferred
* @param _to Address of the recipient of tokens
* @param _value Amount of tokens being transferred
*/
/* solium-disable-next-line function-order */
function transfer(address _token, address _to, uint256 _value)
external
authP(TRANSFER_ROLE, arr(_token, _to, _value))
{
require(_value > 0, ERROR_TRANSFER_VALUE_ZERO);
if (_token == ETH) {
require(_to.send(_value), ERROR_SEND_REVERTED);
} else {
require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED);
}
emit VaultTransfer(_token, _to, _value);
}
function balance(address _token) public view returns (uint256) {
if (_token == ETH) {
return address(this).balance;
} else {
return ERC20(_token).staticBalanceOf(address(this));
}
}
/**
* @dev Disable recovery escape hatch, as it could be used
* maliciously to transfer funds away from the vault
*/
function allowRecoverability(address) public view returns (bool) {
return false;
}
function _deposit(address _token, uint256 _value) internal {
require(isDepositable(), ERROR_NOT_DEPOSITABLE);
require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO);
if (_token == ETH) {
// Deposit is implicit in this case
require(msg.value == _value, ERROR_VALUE_MISMATCH);
} else {
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _value),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
emit VaultDeposit(_token, msg.sender, _value);
}
}
// File: @aragon/os/contracts/common/IForwarder.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IForwarder {
function isForwarder() external pure returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function canForward(address sender, bytes evmCallScript) public view returns (bool);
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function forward(bytes evmCallScript) public;
}
// File: @aragon/apps-agent/contracts/Agent.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault {
/* Hardcoded constants to save gas
bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE");
bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE");
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE");
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE");
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE");
bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE");
bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE");
*/
bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4;
bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694;
bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa;
bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a;
bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c;
bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c;
bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f;
uint256 public constant PROTECTED_TOKENS_CAP = 10;
bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7;
string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED";
string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED";
string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED";
string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED";
string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20";
string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED";
string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED";
string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF";
string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD";
mapping (bytes32 => bool) public isPresigned;
address public designatedSigner;
address[] public protectedTokens;
event SafeExecute(address indexed sender, address indexed target, bytes data);
event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data);
event AddProtectedToken(address indexed token);
event RemoveProtectedToken(address indexed token);
event PresignHash(address indexed sender, bytes32 indexed hash);
event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner);
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'`
* @param _target Address where the action is being executed
* @param _ethValue Amount of ETH from the contract that is sent with the action
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function execute(address _target, uint256 _ethValue, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
bool result = _target.call.value(_ethValue)(_data);
if (result) {
emit Execute(msg.sender, _target, _ethValue, _data);
}
assembly {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, returndatasize) }
default { return(ptr, returndatasize) }
}
}
/**
* @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent
* @param _target Address where the action is being executed
* @param _data Calldata for the action
* @return Exits call frame forwarding the return data of the executed call (either error or success data)
*/
function safeExecute(address _target, bytes _data)
external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context
authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs
{
uint256 protectedTokensLength = protectedTokens.length;
address[] memory protectedTokens_ = new address[](protectedTokensLength);
uint256[] memory balances = new uint256[](protectedTokensLength);
for (uint256 i = 0; i < protectedTokensLength; i++) {
address token = protectedTokens[i];
require(_target != token, ERROR_TARGET_PROTECTED);
// we copy the protected tokens array to check whether the storage array has been modified during the underlying call
protectedTokens_[i] = token;
// we copy the balances to check whether they have been modified during the underlying call
balances[i] = balance(token);
}
bool result = _target.call(_data);
bytes32 ptr;
uint256 size;
assembly {
size := returndatasize
ptr := mload(0x40)
mstore(0x40, add(ptr, returndatasize))
returndatacopy(ptr, 0, returndatasize)
}
if (result) {
// if the underlying call has succeeded, we check that the protected tokens
// and their balances have not been modified and return the call's return data
require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED);
for (uint256 j = 0; j < protectedTokensLength; j++) {
require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED);
require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED);
}
emit SafeExecute(msg.sender, _target, _data);
assembly {
return(ptr, size)
}
} else {
// if the underlying call has failed, we revert and forward returned error data
assembly {
revert(ptr, size)
}
}
}
/**
* @notice Add `_token.symbol(): string` to the list of protected tokens
* @param _token Address of the token to be protected
*/
function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED);
require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20);
require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED);
_addProtectedToken(_token);
}
/**
* @notice Remove `_token.symbol(): string` from the list of protected tokens
* @param _token Address of the token to be unprotected
*/
function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) {
require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED);
_removeProtectedToken(_token);
}
/**
* @notice Pre-sign hash `_hash`
* @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()'
*/
function presignHash(bytes32 _hash)
external
authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash))
{
isPresigned[_hash] = true;
emit PresignHash(msg.sender, _hash);
}
/**
* @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app
* @param _designatedSigner Address that will be able to sign messages on behalf of the app
*/
function setDesignatedSigner(address _designatedSigner)
external
authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner))
{
// Prevent an infinite loop by setting the app itself as its designated signer.
// An undetectable loop can be created by setting a different contract as the
// designated signer which calls back into `isValidSignature`.
// Given that `isValidSignature` is always called with just 50k gas, the max
// damage of the loop is wasting 50k gas.
require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF);
address oldDesignatedSigner = designatedSigner;
designatedSigner = _designatedSigner;
emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner);
}
// Forwarding fns
/**
* @notice Tells whether the Agent app is a forwarder or not
* @dev IForwarder interface conformance
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute the script as the Agent app
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = ""; // no input
address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything
runScript(_evmScript, input, blacklist);
// We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful
}
/**
* @notice Tells whether `_sender` can forward actions or not
* @dev IForwarder interface conformance
* @param _sender Address of the account intending to forward an action
* @return True if the given address can run scripts, false otherwise
*/
function canForward(address _sender, bytes _evmScript) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript)));
}
// ERC-165 conformance
/**
* @notice Tells whether this contract supports a given ERC-165 interface
* @param _interfaceId Interface bytes to check
* @return True if this contract supports the interface
*/
function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {
return
_interfaceId == ERC1271_INTERFACE_ID ||
_interfaceId == ERC165_INTERFACE_ID;
}
// ERC-1271 conformance
/**
* @notice Tells whether a signature is seen as valid by this contract through ERC-1271
* @param _hash Arbitrary length data signed on the behalf of address (this)
* @param _signature Signature byte array associated with _data
* @return The ERC-1271 magic value if the signature is valid
*/
function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) {
// Short-circuit in case the hash was presigned. Optimization as performing calls
// and ecrecover is more expensive than an SLOAD.
if (isPresigned[_hash]) {
return returnIsValidSignatureMagicNumber(true);
}
bool isValid;
if (designatedSigner == address(0)) {
isValid = false;
} else {
isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature);
}
return returnIsValidSignatureMagicNumber(isValid);
}
// Getters
function getProtectedTokensLength() public view isInitialized returns (uint256) {
return protectedTokens.length;
}
// Internal fns
function _addProtectedToken(address _token) internal {
protectedTokens.push(_token);
emit AddProtectedToken(_token);
}
function _removeProtectedToken(address _token) internal {
protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1];
protectedTokens.length--;
emit RemoveProtectedToken(_token);
}
function _isERC20(address _token) internal view returns (bool) {
if (!isContract(_token)) {
return false;
}
// Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now)
balance(_token);
return true;
}
function _protectedTokenIndex(address _token) internal view returns (uint256) {
for (uint i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return i;
}
}
revert(ERROR_TOKEN_NOT_PROTECTED);
}
function _tokenIsProtected(address _token) internal view returns (bool) {
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (protectedTokens[i] == _token) {
return true;
}
}
return false;
}
function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_evmScript)));
}
function _getSig(bytes _data) internal pure returns (bytes4 sig) {
if (_data.length < 4) {
return;
}
assembly { sig := mload(add(_data, 0x20)) }
}
}
// File: @aragon/os/contracts/lib/math/SafeMath.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/os/contracts/lib/math/SafeMath64.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules
// Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417
pragma solidity ^0.4.24;
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// File: @aragon/apps-shared-minime/contracts/ITokenController.sol
pragma solidity ^0.4.24;
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) external returns(bool);
}
// File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol
pragma solidity ^0.4.24;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () external payable {
require(isContract(controller));
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: @aragon/apps-voting/contracts/Voting.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Voting is IForwarder, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE");
bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE");
bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE";
string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS";
string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS";
string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS";
string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG";
string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG";
string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE";
string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE";
string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD";
string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER";
enum VoterState { Absent, Yea, Nay }
struct Vote {
bool executed;
uint64 startDate;
uint64 snapshotBlock;
uint64 supportRequiredPct;
uint64 minAcceptQuorumPct;
uint256 yea;
uint256 nay;
uint256 votingPower;
bytes executionScript;
mapping (address => VoterState) voters;
}
MiniMeToken public token;
uint64 public supportRequiredPct;
uint64 public minAcceptQuorumPct;
uint64 public voteTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => Vote) internal votes;
uint256 public votesLength;
event StartVote(uint256 indexed voteId, address indexed creator, string metadata);
event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake);
event ExecuteVote(uint256 indexed voteId);
event ChangeSupportRequired(uint64 supportRequiredPct);
event ChangeMinQuorum(uint64 minAcceptQuorumPct);
modifier voteExists(uint256 _voteId) {
require(_voteId < votesLength, ERROR_NO_VOTE);
_;
}
/**
* @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)`
* @param _token MiniMeToken Address that will be used as governance token
* @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%)
* @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision)
*/
function initialize(
MiniMeToken _token,
uint64 _supportRequiredPct,
uint64 _minAcceptQuorumPct,
uint64 _voteTime
)
external
onlyInit
{
initialized();
require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG);
token = _token;
supportRequiredPct = _supportRequiredPct;
minAcceptQuorumPct = _minAcceptQuorumPct;
voteTime = _voteTime;
}
/**
* @notice Change required support to `@formatPct(_supportRequiredPct)`%
* @param _supportRequiredPct New required support
*/
function changeSupportRequiredPct(uint64 _supportRequiredPct)
external
authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct)))
{
require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS);
require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG);
supportRequiredPct = _supportRequiredPct;
emit ChangeSupportRequired(_supportRequiredPct);
}
/**
* @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`%
* @param _minAcceptQuorumPct New acceptance quorum
*/
function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct)
external
authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct)))
{
require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS);
minAcceptQuorumPct = _minAcceptQuorumPct;
emit ChangeMinQuorum(_minAcceptQuorumPct);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @return voteId Id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) {
return _newVote(_executionScript, _metadata, true, true);
}
/**
* @notice Create a new vote about "`_metadata`"
* @param _executionScript EVM script to be executed on approval
* @param _metadata Vote metadata
* @param _castVote Whether to also cast newly created vote
* @param _executesIfDecided Whether to also immediately execute newly created vote if decided
* @return voteId id for newly created vote
*/
function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
external
auth(CREATE_VOTES_ROLE)
returns (uint256 voteId)
{
return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided);
}
/**
* @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
* @param _supports Whether voter supports the vote
* @param _executesIfDecided Whether the vote should execute its action if it becomes decided
*/
function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) {
require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE);
_vote(_voteId, _supports, msg.sender, _executesIfDecided);
}
/**
* @notice Execute vote #`_voteId`
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
* @param _voteId Id for vote
*/
function executeVote(uint256 _voteId) external voteExists(_voteId) {
_executeVote(_voteId);
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Creates a vote to execute the desired action, and casts a support vote if possible
* @dev IForwarder interface conformance
* @param _evmScript Start vote with script
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
_newVote(_evmScript, "", true, true);
}
function canForward(address _sender, bytes) public view returns (bool) {
// Note that `canPerform()` implicitly does an initialization check itself
return canPerform(_sender, CREATE_VOTES_ROLE, arr());
}
// Getter fns
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) {
return _canExecute(_voteId);
}
/**
* @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be
* created via `newVote(),` which requires initialization
*/
function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) {
return _canVote(_voteId, _voter);
}
function getVote(uint256 _voteId)
public
view
voteExists(_voteId)
returns (
bool open,
bool executed,
uint64 startDate,
uint64 snapshotBlock,
uint64 supportRequired,
uint64 minAcceptQuorum,
uint256 yea,
uint256 nay,
uint256 votingPower,
bytes script
)
{
Vote storage vote_ = votes[_voteId];
open = _isVoteOpen(vote_);
executed = vote_.executed;
startDate = vote_.startDate;
snapshotBlock = vote_.snapshotBlock;
supportRequired = vote_.supportRequiredPct;
minAcceptQuorum = vote_.minAcceptQuorumPct;
yea = vote_.yea;
nay = vote_.nay;
votingPower = vote_.votingPower;
script = vote_.executionScript;
}
function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) {
return votes[_voteId].voters[_voter];
}
// Internal fns
function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided)
internal
returns (uint256 voteId)
{
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
voteId = votesLength++;
Vote storage vote_ = votes[voteId];
vote_.startDate = getTimestamp64();
vote_.snapshotBlock = snapshotBlock;
vote_.supportRequiredPct = supportRequiredPct;
vote_.minAcceptQuorumPct = minAcceptQuorumPct;
vote_.votingPower = votingPower;
vote_.executionScript = _executionScript;
emit StartVote(voteId, msg.sender, _metadata);
if (_castVote && _canVote(voteId, msg.sender)) {
_vote(voteId, true, msg.sender, _executesIfDecided);
}
}
function _vote(
uint256 _voteId,
bool _supports,
address _voter,
bool _executesIfDecided
) internal
{
Vote storage vote_ = votes[_voteId];
// This could re-enter, though we can assume the governance token is not malicious
uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock);
VoterState state = vote_.voters[_voter];
// If voter had previously voted, decrease count
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
vote_.nay = vote_.nay.sub(voterStake);
}
if (_supports) {
vote_.yea = vote_.yea.add(voterStake);
} else {
vote_.nay = vote_.nay.add(voterStake);
}
vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay;
emit CastVote(_voteId, _voter, _supports, voterStake);
if (_executesIfDecided && _canExecute(_voteId)) {
// We've already checked if the vote can be executed with `_canExecute()`
_unsafeExecuteVote(_voteId);
}
}
function _executeVote(uint256 _voteId) internal {
require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE);
_unsafeExecuteVote(_voteId);
}
/**
* @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed
*/
function _unsafeExecuteVote(uint256 _voteId) internal {
Vote storage vote_ = votes[_voteId];
vote_.executed = true;
bytes memory input = new bytes(0); // TODO: Consider input for voting scripts
runScript(vote_.executionScript, input, new address[](0));
emit ExecuteVote(_voteId);
}
function _canExecute(uint256 _voteId) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
if (vote_.executed) {
return false;
}
// Voting is already decided
if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) {
return true;
}
// Vote ended?
if (_isVoteOpen(vote_)) {
return false;
}
// Has enough support?
uint256 totalVotes = vote_.yea.add(vote_.nay);
if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) {
return false;
}
// Has min quorum?
if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) {
return false;
}
return true;
}
function _canVote(uint256 _voteId, address _voter) internal view returns (bool) {
Vote storage vote_ = votes[_voteId];
return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0;
}
function _isVoteOpen(Vote storage vote_) internal view returns (bool) {
return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed;
}
/**
* @dev Calculates whether `_value` is more than a percentage `_pct` of `_total`
*/
function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) {
if (_total == 0) {
return false;
}
uint256 computedPct = _value.mul(PCT_BASE) / _total;
return computedPct > _pct;
}
}
// File: @aragon/ppf-contracts/contracts/IFeed.sol
pragma solidity ^0.4.18;
interface IFeed {
function ratePrecision() external pure returns (uint256);
function get(address base, address quote) external view returns (uint128 xrt, uint64 when);
}
// File: @aragon/apps-finance/contracts/Finance.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Finance is EtherTokenConstant, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
using SafeERC20 for ERC20;
bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE");
bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE");
bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE");
bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE");
bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE");
uint256 internal constant NO_SCHEDULED_PAYMENT = 0;
uint256 internal constant NO_TRANSACTION = 0;
uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20;
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
uint64 internal constant MINIMUM_PERIOD = uint64(1 days);
string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION";
string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT";
string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION";
string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD";
string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT";
string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT";
string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO";
string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO";
string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO";
string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE";
string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO";
string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO";
string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH";
string private constant ERROR_BUDGET = "FINANCE_BUDGET";
string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM";
string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME";
string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER";
string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT";
string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED";
string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE";
string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET";
// Order optimized for storage
struct ScheduledPayment {
address token;
address receiver;
address createdBy;
bool inactive;
uint256 amount;
uint64 initialPaymentTime;
uint64 interval;
uint64 maxExecutions;
uint64 executions;
}
// Order optimized for storage
struct Transaction {
address token;
address entity;
bool isIncoming;
uint256 amount;
uint256 paymentId;
uint64 paymentExecutionNumber;
uint64 date;
uint64 periodId;
}
struct TokenStatement {
uint256 expenses;
uint256 income;
}
struct Period {
uint64 startTime;
uint64 endTime;
uint256 firstTransactionId;
uint256 lastTransactionId;
mapping (address => TokenStatement) tokenStatement;
}
struct Settings {
uint64 periodDuration;
mapping (address => uint256) budgets;
mapping (address => bool) hasBudget;
}
Vault public vault;
Settings internal settings;
// We are mimicing arrays, we use mappings instead to make app upgrade more graceful
mapping (uint256 => ScheduledPayment) internal scheduledPayments;
// Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not
// linked to a scheduled payment
uint256 public paymentsNextIndex;
mapping (uint256 => Transaction) internal transactions;
uint256 public transactionsNextIndex;
mapping (uint64 => Period) internal periods;
uint64 public periodsLength;
event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds);
event SetBudget(address indexed token, uint256 amount, bool hasBudget);
event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference);
event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference);
event ChangePaymentState(uint256 indexed paymentId, bool active);
event ChangePeriodDuration(uint64 newDuration);
event PaymentFailure(uint256 paymentId);
// Modifier used by all methods that impact accounting to make sure accounting period
// is changed before the operation if needed
// NOTE: its use **MUST** be accompanied by an initialization check
modifier transitionsPeriod {
bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions());
require(completeTransition, ERROR_COMPLETE_TRANSITION);
_;
}
modifier scheduledPaymentExists(uint256 _paymentId) {
require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT);
_;
}
modifier transactionExists(uint256 _transactionId) {
require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION);
_;
}
modifier periodExists(uint64 _periodId) {
require(_periodId < periodsLength, ERROR_NO_PERIOD);
_;
}
/**
* @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever
* @dev Send ETH to Vault. Send all the available balance.
*/
function () external payable isInitialized transitionsPeriod {
require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
_deposit(
ETH,
msg.value,
"Ether transfer to Finance app",
msg.sender,
true
);
}
/**
* @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)`
* @param _vault Address of the vault Finance will rely on (non changeable)
* @param _periodDuration Duration in seconds of each period
*/
function initialize(Vault _vault, uint64 _periodDuration) external onlyInit {
initialized();
require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT);
vault = _vault;
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
// Reserve the first scheduled payment index as an unused index for transactions not linked
// to a scheduled payment
scheduledPayments[0].inactive = true;
paymentsNextIndex = 1;
// Reserve the first transaction index as an unused index for periods with no transactions
transactionsNextIndex = 1;
// Start the first period
_newPeriod(getTimestamp64());
}
/**
* @notice Deposit `@tokenAmount(_token, _amount)`
* @dev Deposit for approved ERC20 tokens or ETH
* @param _token Address of deposited token
* @param _amount Amount of tokens sent
* @param _reference Reason for payment
*/
function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod {
require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
if (_token == ETH) {
// Ensure that the ETH sent with the transaction equals the amount in the deposit
require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH);
}
_deposit(
_token,
_amount,
_reference,
msg.sender,
true
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`'
* @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256`
* as its interval auth parameter (as a sentinel value for "never repeating").
* While this protects against most cases (you typically want to set a baseline requirement
* for interval time), it does mean users will have to explicitly check for this case when
* granting a permission that includes a upperbound requirement on the interval time.
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _reference String detailing payment reason
*/
function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference)
external
// Use MAX_UINT256 as the interval parameter, as this payment will never repeat
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp()))
transitionsPeriod
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
_makePaymentTransaction(
_token,
_receiver,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created
0, // also unrelated to any payment executions
_reference
);
}
/**
* @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)`
* @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used
* @param _token Address of token for payment
* @param _receiver Address that will receive payment
* @param _amount Tokens that are paid every time the payment is due
* @param _initialPaymentTime Timestamp for when the first payment is done
* @param _interval Number of seconds that need to pass between payment transactions
* @param _maxExecutions Maximum instances a payment can be executed
* @param _reference String detailing payment reason
*/
function newScheduledPayment(
address _token,
address _receiver,
uint256 _amount,
uint64 _initialPaymentTime,
uint64 _interval,
uint64 _maxExecutions,
string _reference
)
external
// Payment time parameter is left as the last param as it was added later
authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime)))
transitionsPeriod
returns (uint256 paymentId)
{
require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO);
require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO);
require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO);
// Token budget must not be set at all or allow at least one instance of this payment each period
require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET);
// Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead
if (_maxExecutions == 1) {
require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE);
}
paymentId = paymentsNextIndex++;
emit NewPayment(paymentId, _receiver, _maxExecutions, _reference);
ScheduledPayment storage payment = scheduledPayments[paymentId];
payment.token = _token;
payment.receiver = _receiver;
payment.amount = _amount;
payment.initialPaymentTime = _initialPaymentTime;
payment.interval = _interval;
payment.maxExecutions = _maxExecutions;
payment.createdBy = msg.sender;
// We skip checking how many times the new payment was executed to allow creating new
// scheduled payments before having enough vault balance
_executePayment(paymentId);
}
/**
* @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period
* @param _periodDuration Duration in seconds for accounting periods
*/
function setPeriodDuration(uint64 _periodDuration)
external
authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration)))
transitionsPeriod
{
require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT);
settings.periodDuration = _periodDuration;
emit ChangePeriodDuration(_periodDuration);
}
/**
* @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately
* @param _token Address for token
* @param _amount New budget amount
*/
function setBudget(
address _token,
uint256 _amount
)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = _amount;
if (!settings.hasBudget[_token]) {
settings.hasBudget[_token] = true;
}
emit SetBudget(_token, _amount, true);
}
/**
* @notice Remove spending limit for `_token.symbol(): string`, effective immediately
* @param _token Address for token
*/
function removeBudget(address _token)
external
authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0)))
transitionsPeriod
{
settings.budgets[_token] = 0;
settings.hasBudget[_token] = false;
emit SetBudget(_token, 0, false);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Executes any payment (requires role)
* @param _paymentId Identifier for payment
*/
function executePayment(uint256 _paymentId)
external
authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount))
scheduledPaymentExists(_paymentId)
transitionsPeriod
{
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice Execute pending payment #`_paymentId`
* @dev Always allow receiver of a payment to trigger execution
* Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
* @param _paymentId Identifier for payment
*/
function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod {
require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER);
_executePaymentAtLeastOnce(_paymentId);
}
/**
* @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId`
* @dev Note that we do not require this action to transition periods, as it doesn't directly
* impact any accounting periods.
* Not having to transition periods also makes disabling payments easier to prevent funds
* from being pulled out in the event of a breach.
* @param _paymentId Identifier for payment
* @param _active Whether it will be active or inactive
*/
function setPaymentStatus(uint256 _paymentId, bool _active)
external
authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0)))
scheduledPaymentExists(_paymentId)
{
scheduledPayments[_paymentId].inactive = !_active;
emit ChangePaymentState(_paymentId, _active);
}
/**
* @notice Send tokens held in this contract to the Vault
* @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens.
* This contract should never receive tokens with a simple transfer call, but in case it
* happens, this function allows for their recovery.
* @param _token Token whose balance is going to be transferred.
*/
function recoverToVault(address _token) external isInitialized transitionsPeriod {
uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this));
require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO);
_deposit(
_token,
amount,
"Recover to Vault",
address(this),
false
);
}
/**
* @notice Transition accounting period if needed
* @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions
* param is provided. If more than the specified number of periods need to be transitioned,
* it will return false.
* @param _maxTransitions Maximum periods that can be transitioned
* @return success Boolean indicating whether the accounting period is the correct one (if false,
* maxTransitions was surpased and another call is needed)
*/
function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) {
return _tryTransitionAccountingPeriod(_maxTransitions);
}
// Getter fns
/**
* @dev Disable recovery escape hatch if the app has been initialized, as it could be used
* maliciously to transfer funds in the Finance app to another Vault
* finance#recoverToVault() should be used to recover funds to the Finance's vault
*/
function allowRecoverability(address) public view returns (bool) {
return !hasInitialized();
}
function getPayment(uint256 _paymentId)
public
view
scheduledPaymentExists(_paymentId)
returns (
address token,
address receiver,
uint256 amount,
uint64 initialPaymentTime,
uint64 interval,
uint64 maxExecutions,
bool inactive,
uint64 executions,
address createdBy
)
{
ScheduledPayment storage payment = scheduledPayments[_paymentId];
token = payment.token;
receiver = payment.receiver;
amount = payment.amount;
initialPaymentTime = payment.initialPaymentTime;
interval = payment.interval;
maxExecutions = payment.maxExecutions;
executions = payment.executions;
inactive = payment.inactive;
createdBy = payment.createdBy;
}
function getTransaction(uint256 _transactionId)
public
view
transactionExists(_transactionId)
returns (
uint64 periodId,
uint256 amount,
uint256 paymentId,
uint64 paymentExecutionNumber,
address token,
address entity,
bool isIncoming,
uint64 date
)
{
Transaction storage transaction = transactions[_transactionId];
token = transaction.token;
entity = transaction.entity;
isIncoming = transaction.isIncoming;
date = transaction.date;
periodId = transaction.periodId;
amount = transaction.amount;
paymentId = transaction.paymentId;
paymentExecutionNumber = transaction.paymentExecutionNumber;
}
function getPeriod(uint64 _periodId)
public
view
periodExists(_periodId)
returns (
bool isCurrent,
uint64 startTime,
uint64 endTime,
uint256 firstTransactionId,
uint256 lastTransactionId
)
{
Period storage period = periods[_periodId];
isCurrent = _currentPeriodId() == _periodId;
startTime = period.startTime;
endTime = period.endTime;
firstTransactionId = period.firstTransactionId;
lastTransactionId = period.lastTransactionId;
}
function getPeriodTokenStatement(uint64 _periodId, address _token)
public
view
periodExists(_periodId)
returns (uint256 expenses, uint256 income)
{
TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token];
expenses = tokenStatement.expenses;
income = tokenStatement.income;
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function currentPeriodId() public view isInitialized returns (uint64) {
return _currentPeriodId();
}
/**
* @dev We have to check for initialization as periods are only valid after initializing
*/
function getPeriodDuration() public view isInitialized returns (uint64) {
return settings.periodDuration;
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) {
budget = settings.budgets[_token];
hasBudget = settings.hasBudget[_token];
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function getRemainingBudget(address _token) public view isInitialized returns (uint256) {
return _getRemainingBudget(_token);
}
/**
* @dev We have to check for initialization as budgets are only valid after initializing
*/
function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) {
return _canMakePayment(_token, _amount);
}
/**
* @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new
* scheduled payments can only be created via `newScheduledPayment(),` which requires initialization
*/
function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) {
return _nextPaymentTime(_paymentId);
}
// Internal fns
function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal {
_recordIncomingTransaction(
_token,
_sender,
_amount,
_reference
);
if (_token == ETH) {
vault.deposit.value(_amount)(ETH, _amount);
} else {
// First, transfer the tokens to Finance if necessary
// External deposit will be false when the assets were already in the Finance app
// and just need to be transferred to the Vault
if (_isExternalDeposit) {
// This assumes the sender has approved the tokens for Finance
require(
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount),
ERROR_TOKEN_TRANSFER_FROM_REVERTED
);
}
// Approve the tokens for the Vault (it does the actual transferring)
require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED);
// Finally, initiate the deposit
vault.deposit(_token, _amount);
}
}
function _executePayment(uint256 _paymentId) internal returns (uint256) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
require(!payment.inactive, ERROR_PAYMENT_INACTIVE);
uint64 paid = 0;
while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) {
if (!_canMakePayment(payment.token, payment.amount)) {
emit PaymentFailure(_paymentId);
break;
}
// The while() predicate prevents these two from ever overflowing
payment.executions += 1;
paid += 1;
// We've already checked the remaining budget with `_canMakePayment()`
_unsafeMakePaymentTransaction(
payment.token,
payment.receiver,
payment.amount,
_paymentId,
payment.executions,
""
);
}
return paid;
}
function _executePaymentAtLeastOnce(uint256 _paymentId) internal {
uint256 paid = _executePayment(_paymentId);
if (paid == 0) {
if (_nextPaymentTime(_paymentId) <= getTimestamp64()) {
revert(ERROR_EXECUTE_PAYMENT_NUM);
} else {
revert(ERROR_EXECUTE_PAYMENT_TIME);
}
}
}
function _makePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET);
_unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference);
}
/**
* @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the
* remaining budget
*/
function _unsafeMakePaymentTransaction(
address _token,
address _receiver,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
_recordTransaction(
false,
_token,
_receiver,
_amount,
_paymentId,
_paymentExecutionNumber,
_reference
);
vault.transfer(_token, _receiver, _amount);
}
function _newPeriod(uint64 _startTime) internal returns (Period storage) {
// There should be no way for this to overflow since each period is at least one day
uint64 newPeriodId = periodsLength++;
Period storage period = periods[newPeriodId];
period.startTime = _startTime;
// Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime
// to MAX_UINT64 (let's assume that's the end of time for now).
uint64 endTime = _startTime + settings.periodDuration - 1;
if (endTime < _startTime) { // overflowed
endTime = MAX_UINT64;
}
period.endTime = endTime;
emit NewPeriod(newPeriodId, period.startTime, period.endTime);
return period;
}
function _recordIncomingTransaction(
address _token,
address _sender,
uint256 _amount,
string _reference
)
internal
{
_recordTransaction(
true, // incoming transaction
_token,
_sender,
_amount,
NO_SCHEDULED_PAYMENT, // unrelated to any existing payment
0, // and no payment executions
_reference
);
}
function _recordTransaction(
bool _incoming,
address _token,
address _entity,
uint256 _amount,
uint256 _paymentId,
uint64 _paymentExecutionNumber,
string _reference
)
internal
{
uint64 periodId = _currentPeriodId();
TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token];
if (_incoming) {
tokenStatement.income = tokenStatement.income.add(_amount);
} else {
tokenStatement.expenses = tokenStatement.expenses.add(_amount);
}
uint256 transactionId = transactionsNextIndex++;
Transaction storage transaction = transactions[transactionId];
transaction.token = _token;
transaction.entity = _entity;
transaction.isIncoming = _incoming;
transaction.amount = _amount;
transaction.paymentId = _paymentId;
transaction.paymentExecutionNumber = _paymentExecutionNumber;
transaction.date = getTimestamp64();
transaction.periodId = periodId;
Period storage period = periods[periodId];
if (period.firstTransactionId == NO_TRANSACTION) {
period.firstTransactionId = transactionId;
}
emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference);
}
function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) {
Period storage currentPeriod = periods[_currentPeriodId()];
uint64 timestamp = getTimestamp64();
// Transition periods if necessary
while (timestamp > currentPeriod.endTime) {
if (_maxTransitions == 0) {
// Required number of transitions is over allowed number, return false indicating
// it didn't fully transition
return false;
}
// We're already protected from underflowing above
_maxTransitions -= 1;
// If there were any transactions in period, record which was the last
// In case 0 transactions occured, first and last tx id will be 0
if (currentPeriod.firstTransactionId != NO_TRANSACTION) {
currentPeriod.lastTransactionId = transactionsNextIndex.sub(1);
}
// New period starts at end time + 1
currentPeriod = _newPeriod(currentPeriod.endTime.add(1));
}
return true;
}
function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) {
return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount;
}
function _currentPeriodId() internal view returns (uint64) {
// There is no way for this to overflow if protected by an initialization check
return periodsLength - 1;
}
function _getRemainingBudget(address _token) internal view returns (uint256) {
if (!settings.hasBudget[_token]) {
return MAX_UINT256;
}
uint256 budget = settings.budgets[_token];
uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses;
// A budget decrease can cause the spent amount to be greater than period budget
// If so, return 0 to not allow more spending during period
if (spent >= budget) {
return 0;
}
// We're already protected from the overflow above
return budget - spent;
}
function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) {
ScheduledPayment storage payment = scheduledPayments[_paymentId];
if (payment.executions >= payment.maxExecutions) {
return MAX_UINT64; // re-executes in some billions of years time... should not need to worry
}
// Split in multiple lines to circumvent linter warning
uint64 increase = payment.executions.mul(payment.interval);
uint64 nextPayment = payment.initialPaymentTime.add(increase);
return nextPayment;
}
// Syntax sugar
function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) {
r = new uint256[](6);
r[0] = uint256(_a);
r[1] = uint256(_b);
r[2] = _c;
r[3] = _d;
r[4] = _e;
r[5] = _f;
}
// Mocked fns (overrided during testing)
// Must be view for mocking purposes
function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; }
}
// File: @aragon/apps-payroll/contracts/Payroll.sol
pragma solidity 0.4.24;
/**
* @title Payroll in multiple currencies
*/
contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
/* Hardcoded constants to save gas
* bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE");
* bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE");
* bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE");
* bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE");
* bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE");
* bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE");
* bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE");
* bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE");
*/
bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e;
bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242;
bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d;
bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae;
bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16;
bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06;
bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302;
bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e;
uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()`
uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout
uint256 internal constant MAX_UINT256 = uint256(-1);
uint64 internal constant MAX_UINT64 = uint64(-1);
string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST";
string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE";
string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH";
string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT";
string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET";
string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS";
string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH";
string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH";
string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN";
string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL";
string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE";
string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID";
string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD";
string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS";
string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST";
string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT";
string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT";
string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE";
string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW";
string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG";
string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT";
enum PaymentType { Payroll, Reimbursement, Bonus }
struct Employee {
address accountAddress; // unique, but can be changed over time
uint256 denominationTokenSalary; // salary per second in denomination Token
uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries
uint256 bonus;
uint256 reimbursements;
uint64 lastPayroll;
uint64 endDate;
address[] allocationTokenAddresses;
mapping(address => uint256) allocationTokens;
}
Finance public finance;
address public denominationToken;
IFeed public feed;
uint64 public rateExpiryTime;
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
uint256 public nextEmployee;
mapping(uint256 => Employee) internal employees; // employee ID -> employee
mapping(address => uint256) internal employeeIds; // employee address -> employee ID
mapping(address => bool) internal allowedTokens;
event AddEmployee(
uint256 indexed employeeId,
address indexed accountAddress,
uint256 initialDenominationSalary,
uint64 startDate,
string role
);
event TerminateEmployee(uint256 indexed employeeId, uint64 endDate);
event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary);
event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount);
event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount);
event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount);
event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress);
event DetermineAllocation(uint256 indexed employeeId);
event SendPayment(
uint256 indexed employeeId,
address indexed accountAddress,
address indexed token,
uint256 amount,
uint256 exchangeRate,
string paymentReference
);
event SetAllowedToken(address indexed token, bool allowed);
event SetPriceFeed(address indexed feed);
event SetRateExpiryTime(uint64 time);
// Check employee exists by ID
modifier employeeIdExists(uint256 _employeeId) {
require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST);
_;
}
// Check employee exists and is still active
modifier employeeActive(uint256 _employeeId) {
// No need to check for existence as _isEmployeeIdActive() is false for non-existent employees
require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE);
_;
}
// Check sender matches an existing employee
modifier employeeMatches {
require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH);
_;
}
/**
* @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)`
* @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake"
* address used by the price feed to denominate fiat currencies
* @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable)
* @param _denominationToken Address of the denomination token used for salary accounting
* @param _priceFeed Address of the price feed
* @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates
*/
function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit {
initialized();
require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT);
finance = _finance;
denominationToken = _denominationToken;
_setPriceFeed(_priceFeed);
_setRateExpiryTime(_rateExpiryTime);
// Employees start at index 1, to allow us to use employees[0] to check for non-existent employees
nextEmployee = 1;
}
/**
* @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens
* @param _token Address of the token to be added or removed from the list of allowed tokens for payments
* @param _allowed Boolean to tell whether the given token should be added or removed from the list
*/
function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) {
require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET);
allowedTokens[_token] = _allowed;
emit SetAllowedToken(_token, _allowed);
}
/**
* @notice Set the price feed for exchange rates to `_feed`
* @param _feed Address of the new price feed instance
*/
function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) {
_setPriceFeed(_feed);
}
/**
* @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)`
* @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert
* @param _time The expiration time in seconds for exchange rates
*/
function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) {
_setRateExpiryTime(_time);
}
/**
* @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)`
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value)
* @param _role Employee's role
*/
function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role)
external
authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate)))
{
_addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @notice Add `_amount` to bonus for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's bonuses in denomination token
*/
function addBonus(uint256 _employeeId, uint256 _amount)
external
authP(ADD_BONUS_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addBonus(_employeeId, _amount);
}
/**
* @notice Add `_amount` to reimbursements for employee #`_employeeId`
* @param _employeeId Employee's identifier
* @param _amount Amount to be added to the employee's reimbursements in denomination token
*/
function addReimbursement(uint256 _employeeId, uint256 _amount)
external
authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount))
employeeActive(_employeeId)
{
_addReimbursement(_employeeId, _amount);
}
/**
* @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second
* @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid
* losing any accrued salary for an employee due to the employer changing their salary.
* @param _employeeId Employee's identifier
* @param _denominationSalary Employee's new salary, per second in denomination token
*/
function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary)
external
authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary))
employeeActive(_employeeId)
{
Employee storage employee = employees[_employeeId];
// Accrue employee's owed salary; don't cap to revert on overflow
uint256 owed = _getOwedSalarySinceLastPayroll(employee, false);
_addAccruedSalary(_employeeId, owed);
// Update employee to track the new salary and payment date
employee.lastPayroll = getTimestamp64();
employee.denominationTokenSalary = _denominationSalary;
emit SetEmployeeSalary(_employeeId, _denominationSalary);
}
/**
* @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)`
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function terminateEmployee(uint256 _employeeId, uint64 _endDate)
external
authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate)))
employeeActive(_employeeId)
{
_terminateEmployee(_employeeId, _endDate);
}
/**
* @notice Change your employee account address to `_newAccountAddress`
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _newAccountAddress New address to receive payments for the requesting employee
*/
function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant {
uint256 employeeId = employeeIds[msg.sender];
address oldAddress = employees[employeeId].accountAddress;
_setEmployeeAddress(employeeId, _newAccountAddress);
// Don't delete the old address until after setting the new address to check that the
// employee specified a new address
delete employeeIds[oldAddress];
emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress);
}
/**
* @notice Set the token distribution for your payments
* @dev Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _tokens Array of token addresses; they must belong to the list of allowed tokens
* @param _distribution Array with each token's corresponding proportions (must be integers summing to 100)
*/
function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant {
// Check array lengthes match
require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS);
require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH);
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
// Delete previous token allocations
address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses;
for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) {
delete employee.allocationTokens[previousAllowedTokenAddresses[j]];
}
delete employee.allocationTokenAddresses;
// Set distributions only if given tokens are allowed
for (uint256 i = 0; i < _tokens.length; i++) {
employee.allocationTokenAddresses.push(_tokens[i]);
employee.allocationTokens[_tokens[i]] = _distribution[i];
}
_ensureEmployeeTokenAllocationsIsValid(employee);
emit DetermineAllocation(employeeId);
}
/**
* @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'`
* @dev Reverts if no payments were made.
* Initialization check is implicitly provided by `employeeMatches` as new employees can
* only be added via `addEmployee(),` which requires initialization.
* As the employee is allowed to call this, we enforce non-reentrancy.
* @param _type Payment type being requested (Payroll, Reimbursement or Bonus)
* @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all.
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
*/
function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant {
uint256 paymentAmount;
uint256 employeeId = employeeIds[msg.sender];
Employee storage employee = employees[employeeId];
_ensureEmployeeTokenAllocationsIsValid(employee);
require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH);
// Do internal employee accounting
if (_type == PaymentType.Payroll) {
// Salary is capped here to avoid reverting at this point if it becomes too big
// (so employees aren't DDOSed if their salaries get too large)
// If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly
uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee);
paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount);
_updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount);
} else if (_type == PaymentType.Reimbursement) {
uint256 owedReimbursements = employee.reimbursements;
paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount);
employee.reimbursements = owedReimbursements.sub(paymentAmount);
} else if (_type == PaymentType.Bonus) {
uint256 owedBonusAmount = employee.bonus;
paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount);
employee.bonus = owedBonusAmount.sub(paymentAmount);
} else {
revert(ERROR_INVALID_PAYMENT_TYPE);
}
// Actually transfer the owed funds
require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID);
_removeEmployeeIfTerminatedAndPaidOut(employeeId);
}
// Forwarding fns
/**
* @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not.
* @return Always true
*/
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as an active employee
* @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the Finance app to the blacklist to disallow employees from executing actions on the
// Finance app from Payroll's context (since Payroll requires permissions on Finance)
address[] memory blacklist = new address[](1);
blacklist[0] = address(finance);
runScript(_evmScript, input, blacklist);
}
/**
* @dev IForwarder interface conformance. Tells whether a given address can forward actions or not.
* @param _sender Address of the account intending to forward an action
* @return True if the given address is an active employee, false otherwise
*/
function canForward(address _sender, bytes) public view returns (bool) {
return _isEmployeeIdActive(employeeIds[_sender]);
}
// Getter fns
/**
* @dev Return employee's identifier by their account address
* @param _accountAddress Employee's address to receive payments
* @return Employee's identifier
*/
function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) {
require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST);
return employeeIds[_accountAddress];
}
/**
* @dev Return all information for employee by their ID
* @param _employeeId Employee's identifier
* @return Employee's address to receive payments
* @return Employee's salary, per second in denomination token
* @return Employee's accrued salary
* @return Employee's bonus amount
* @return Employee's reimbursements amount
* @return Employee's last payment date
* @return Employee's termination date (max uint64 if none)
* @return Employee's allowed payment tokens
*/
function getEmployee(uint256 _employeeId)
public
view
employeeIdExists(_employeeId)
returns (
address accountAddress,
uint256 denominationSalary,
uint256 accruedSalary,
uint256 bonus,
uint256 reimbursements,
uint64 lastPayroll,
uint64 endDate,
address[] allocationTokens
)
{
Employee storage employee = employees[_employeeId];
accountAddress = employee.accountAddress;
denominationSalary = employee.denominationTokenSalary;
accruedSalary = employee.accruedSalary;
bonus = employee.bonus;
reimbursements = employee.reimbursements;
lastPayroll = employee.lastPayroll;
endDate = employee.endDate;
allocationTokens = employee.allocationTokenAddresses;
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) {
return _getTotalOwedCappedSalary(employees[_employeeId]);
}
/**
* @dev Get an employee's payment allocation for a token
* @param _employeeId Employee's identifier
* @param _token Token to query the payment allocation for
* @return Employee's payment allocation for the token being queried
*/
function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) {
return employees[_employeeId].allocationTokens[_token];
}
/**
* @dev Check if a token is allowed to be used for payments
* @param _token Address of the token to be checked
* @return True if the given token is allowed, false otherwise
*/
function isTokenAllowed(address _token) public view isInitialized returns (bool) {
return allowedTokens[_token];
}
// Internal fns
/**
* @dev Set the price feed used for exchange rates
* @param _feed Address of the new price feed instance
*/
function _setPriceFeed(IFeed _feed) internal {
require(isContract(_feed), ERROR_FEED_NOT_CONTRACT);
feed = _feed;
emit SetPriceFeed(feed);
}
/**
* @dev Set the exchange rate expiry time in seconds.
* Exchange rates older than the given value won't be accepted for payments and will cause
* payouts to revert.
* @param _time The expiration time in seconds for exchange rates
*/
function _setRateExpiryTime(uint64 _time) internal {
// Require a sane minimum for the rate expiry time
require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT);
rateExpiryTime = _time;
emit SetRateExpiryTime(rateExpiryTime);
}
/**
* @dev Add a new employee to Payroll
* @param _accountAddress Employee's address to receive payroll
* @param _initialDenominationSalary Employee's salary, per second in denomination token
* @param _startDate Employee's starting timestamp in seconds
* @param _role Employee's role
*/
function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal {
uint256 employeeId = nextEmployee++;
_setEmployeeAddress(employeeId, _accountAddress);
Employee storage employee = employees[employeeId];
employee.denominationTokenSalary = _initialDenominationSalary;
employee.lastPayroll = _startDate;
employee.endDate = MAX_UINT64;
emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role);
}
/**
* @dev Add amount to an employee's bonuses
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's bonuses in denomination token
*/
function _addBonus(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.bonus = employee.bonus.add(_amount);
emit AddEmployeeBonus(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's reimbursements
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's reimbursements in denomination token
*/
function _addReimbursement(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.reimbursements = employee.reimbursements.add(_amount);
emit AddEmployeeReimbursement(_employeeId, _amount);
}
/**
* @dev Add amount to an employee's accrued salary
* @param _employeeId Employee's identifier
* @param _amount Amount be added to the employee's accrued salary in denomination token
*/
function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal {
Employee storage employee = employees[_employeeId];
employee.accruedSalary = employee.accruedSalary.add(_amount);
emit AddEmployeeAccruedSalary(_employeeId, _amount);
}
/**
* @dev Set an employee's account address
* @param _employeeId Employee's identifier
* @param _accountAddress Employee's address to receive payroll
*/
function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal {
// Check address is non-null
require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS);
// Check address isn't already being used
require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST);
employees[_employeeId].accountAddress = _accountAddress;
// Create IDs mapping
employeeIds[_accountAddress] = _employeeId;
}
/**
* @dev Terminate employee on end date
* @param _employeeId Employee's identifier
* @param _endDate Termination timestamp in seconds
*/
function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal {
// Prevent past termination dates
require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE);
employees[_employeeId].endDate = _endDate;
emit TerminateEmployee(_employeeId, _endDate);
}
/**
* @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation
* @param _employeeId Employee's identifier
* @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation.
* @param _type Payment type being transferred (Payroll, Reimbursement or Bonus)
* @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens
* @return True if there was at least one token transfer
*/
function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) {
if (_totalAmount == 0) {
return false;
}
Employee storage employee = employees[_employeeId];
address employeeAddress = employee.accountAddress;
string memory paymentReference = _paymentReferenceFor(_type);
address[] storage allocationTokenAddresses = employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
uint256 tokenAllocation = employee.allocationTokens[token];
if (tokenAllocation != uint256(0)) {
// Get the exchange rate for the payout token in denomination token,
// as we do accounting in denomination tokens
uint256 exchangeRate = _getExchangeRateInDenominationToken(token);
require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW);
// Convert amount (in denomination tokens) to payout token and apply allocation
uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation);
// Divide by 100 for the allocation percentage and by the exchange rate precision
tokenAmount = tokenAmount.div(100).div(feed.ratePrecision());
// Finance reverts if the payment wasn't possible
finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference);
emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference);
somethingPaid = true;
}
}
}
/**
* @dev Remove employee if there are no owed funds and employee's end date has been reached
* @param _employeeId Employee's identifier
*/
function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal {
Employee storage employee = employees[_employeeId];
if (
employee.lastPayroll == employee.endDate &&
(employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0)
) {
delete employeeIds[employee.accountAddress];
delete employees[_employeeId];
}
}
/**
* @dev Updates the accrued salary and payroll date of an employee based on a payment amount and
* their currently owed salary since last payroll date
* @param _employee Employee struct in storage
* @param _paymentAmount Amount being paid to the employee
*/
function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal {
uint256 accruedSalary = _employee.accruedSalary;
if (_paymentAmount <= accruedSalary) {
// Employee is only cashing out some previously owed salary so we don't need to update
// their last payroll date
// No need to use SafeMath as we already know _paymentAmount <= accruedSalary
_employee.accruedSalary = accruedSalary - _paymentAmount;
return;
}
// Employee is cashing out some of their currently owed salary so their last payroll date
// needs to be modified based on the amount of salary paid
uint256 currentSalaryPaid = _paymentAmount;
if (accruedSalary > 0) {
// Employee is cashing out a mixed amount between previous and current owed salaries;
// first use up their accrued salary
// No need to use SafeMath here as we already know _paymentAmount > accruedSalary
currentSalaryPaid = _paymentAmount - accruedSalary;
// We finally need to clear their accrued salary
_employee.accruedSalary = 0;
}
uint256 salary = _employee.denominationTokenSalary;
uint256 timeDiff = currentSalaryPaid.div(salary);
// If they're being paid an amount that doesn't match perfectly with the adjusted time
// (up to a seconds' worth of salary), add the second and put the extra remaining salary
// into their accrued salary
uint256 extraSalary = currentSalaryPaid % salary;
if (extraSalary > 0) {
timeDiff = timeDiff.add(1);
_employee.accruedSalary = salary - extraSalary;
}
uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff);
// Even though this function should never receive a currentSalaryPaid value that would
// result in the lastPayrollDate being higher than the current time,
// let's double check to be safe
require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG);
// Already know lastPayrollDate must fit in uint64 from above
_employee.lastPayroll = uint64(lastPayrollDate);
}
/**
* @dev Tell whether an employee is registered in this Payroll or not
* @param _employeeId Employee's identifier
* @return True if the given employee ID belongs to an registered employee, false otherwise
*/
function _employeeExists(uint256 _employeeId) internal view returns (bool) {
return employees[_employeeId].accountAddress != address(0);
}
/**
* @dev Tell whether an employee has a valid token allocation or not.
* A valid allocation is one that sums to 100 and only includes allowed tokens.
* @param _employee Employee struct in storage
* @return Reverts if employee's allocation is invalid
*/
function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view {
uint256 sum = 0;
address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses;
for (uint256 i = 0; i < allocationTokenAddresses.length; i++) {
address token = allocationTokenAddresses[i];
require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN);
sum = sum.add(_employee.allocationTokens[token]);
}
require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL);
}
/**
* @dev Tell whether an employee is still active or not
* @param _employee Employee struct in storage
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeActive(Employee storage _employee) internal view returns (bool) {
return _employee.endDate >= getTimestamp64();
}
/**
* @dev Tell whether an employee id is still active or not
* @param _employeeId Employee's identifier
* @return True if the employee exists and has an end date that has not been reached yet, false otherwise
*/
function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) {
return _isEmployeeActive(employees[_employeeId]);
}
/**
* @dev Get exchange rate for a token based on the denomination token.
* As an example, if the denomination token was USD and ETH's price was 100USD,
* this would return 0.01 * precision rate for ETH.
* @param _token Token to get price of in denomination tokens
* @return Exchange rate (multiplied by the PPF rate precision)
*/
function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) {
// xrt is the number of `_token` that can be exchanged for one `denominationToken`
(uint128 xrt, uint64 when) = feed.get(
denominationToken, // Base (e.g. USD)
_token // Quote (e.g. ETH)
);
// Check the price feed is recent enough
if (getTimestamp64().sub(when) >= rateExpiryTime) {
return 0;
}
return uint256(xrt);
}
/**
* @dev Get owed salary since last payroll for an employee
* @param _employee Employee struct in storage
* @param _capped Safely cap the owed salary at max uint
* @return Owed salary in denomination tokens since last payroll for the employee.
* If _capped is false, it reverts in case of an overflow.
*/
function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) {
uint256 timeDiff = _getOwedPayrollPeriod(_employee);
if (timeDiff == 0) {
return 0;
}
uint256 salary = _employee.denominationTokenSalary;
if (_capped) {
// Return max uint if the result overflows
uint256 result = salary * timeDiff;
return (result / timeDiff != salary) ? MAX_UINT256 : result;
} else {
return salary.mul(timeDiff);
}
}
/**
* @dev Get owed payroll period for an employee
* @param _employee Employee struct in storage
* @return Owed time in seconds since the employee's last payroll date
*/
function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) {
// Get the min of current date and termination date
uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate;
// Make sure we don't revert if we try to get the owed salary for an employee whose last
// payroll date is now or in the future
// This can happen either by adding new employees with start dates in the future, to allow
// us to change their salary before their start date, or by terminating an employee and
// paying out their full owed salary
if (date <= _employee.lastPayroll) {
return 0;
}
// Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check
return uint256(date - _employee.lastPayroll);
}
/**
* @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well.
* The result will be capped to max uint256 to avoid having an overflow.
* @param _employee Employee struct in storage
* @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary.
*/
function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) {
uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount
uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary;
if (totalOwedSalary < currentOwedSalary) {
totalOwedSalary = MAX_UINT256;
}
return totalOwedSalary;
}
/**
* @dev Get payment reference for a given payment type
* @param _type Payment type to query the reference of
* @return Payment reference for the given payment type
*/
function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) {
if (_type == PaymentType.Payroll) {
return "Employee salary";
} else if (_type == PaymentType.Reimbursement) {
return "Employee reimbursement";
} if (_type == PaymentType.Bonus) {
return "Employee bonus";
}
revert(ERROR_INVALID_PAYMENT_TYPE);
}
function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) {
require(_owedAmount > 0, ERROR_NOTHING_PAID);
require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT);
return _requestedAmount > 0 ? _requestedAmount : _owedAmount;
}
}
// File: @aragon/apps-token-manager/contracts/TokenManager.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
/* solium-disable function-order */
pragma solidity 0.4.24;
contract TokenManager is ITokenController, IForwarder, AragonApp {
using SafeMath for uint256;
bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE");
bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE");
bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE");
bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE");
bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE");
uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50;
string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN";
string private constant ERROR_NO_VESTING = "TM_NO_VESTING";
string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER";
string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM";
string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM";
string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS";
string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE";
string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE";
string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED";
string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD";
string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED";
string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED";
struct TokenVesting {
uint256 amount;
uint64 start;
uint64 cliff;
uint64 vesting;
bool revokable;
}
// Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract
MiniMeToken public token;
uint256 public maxAccountTokens;
// We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful
mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
// Other token specific events can be watched on the token address directly (avoids duplication)
event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount);
event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount);
modifier onlyToken() {
require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN);
_;
}
modifier vestingExists(address _holder, uint256 _vestingId) {
// TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function
require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING);
_;
}
/**
* @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''`
* @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller)
* @param _transferable whether the token can be transferred by holders
* @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens)
*/
function initialize(
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
external
onlyInit
{
initialized();
require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER);
token = _token;
maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens;
if (token.transfersEnabled() != _transferable) {
token.enableTransfers(_transferable);
}
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver`
* @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead)
* @param _amount Number of tokens minted
*/
function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) {
require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM);
_mint(_receiver, _amount);
}
/**
* @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager
* @param _amount Number of tokens minted
*/
function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) {
_mint(address(this), _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings
* @param _receiver The address receiving the tokens
* @param _amount Number of tokens transferred
*/
function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) {
_assign(_receiver, _amount);
}
/**
* @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder`
* @param _holder Holder of tokens being burned
* @param _amount Number of tokens being burned
*/
function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) {
// minime.destroyTokens() never returns false, only reverts on failure
token.destroyTokens(_holder, _amount);
}
/**
* @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable)
* @param _receiver The address receiving the tokens, cannot be Token Manager itself
* @param _amount Number of tokens vested
* @param _start Date the vesting calculations start
* @param _cliff Date when the initial portion of tokens are transferable
* @param _vested Date when all tokens are transferable
* @param _revokable Whether the vesting can be revoked by the Token Manager
*/
function assignVested(
address _receiver,
uint256 _amount,
uint64 _start,
uint64 _cliff,
uint64 _vested,
bool _revokable
)
external
authP(ASSIGN_ROLE, arr(_receiver, _amount))
returns (uint256)
{
require(_receiver != address(this), ERROR_VESTING_TO_TM);
require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS);
require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE);
uint256 vestingId = vestingsLengths[_receiver]++;
vestings[_receiver][vestingId] = TokenVesting(
_amount,
_start,
_cliff,
_vested,
_revokable
);
_assign(_receiver, _amount);
emit NewVesting(_receiver, vestingId, _amount);
return vestingId;
}
/**
* @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager
* @param _holder Address whose vesting to revoke
* @param _vestingId Numeric id of the vesting
*/
function revokeVesting(address _holder, uint256 _vestingId)
external
authP(REVOKE_VESTINGS_ROLE, arr(_holder))
vestingExists(_holder, _vestingId)
{
TokenVesting storage v = vestings[_holder][_vestingId];
require(v.revokable, ERROR_VESTING_NOT_REVOKABLE);
uint256 nonVested = _calculateNonVestedTokens(
v.amount,
getTimestamp(),
v.start,
v.cliff,
v.vesting
);
// To make vestingIds immutable over time, we just zero out the revoked vesting
// Clearing this out also allows the token transfer back to the Token Manager to succeed
delete vestings[_holder][_vestingId];
// transferFrom always works as controller
// onTransfer hook always allows if transfering to token controller
require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED);
emit RevokeVesting(_holder, _vestingId, nonVested);
}
// ITokenController fns
// `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token
// contract and are only meant to be called through the managed MiniMe token that gets assigned
// during initialization.
/*
* @dev Notifies the controller about a token transfer allowing the controller to decide whether
* to allow it or react if desired (only callable from the token).
* Initialization check is implicitly provided by `onlyToken()`.
* @param _from The origin of the transfer
* @param _to The destination of the transfer
* @param _amount The amount of the transfer
* @return False if the controller does not authorize the transfer
*/
function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) {
return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount;
}
/**
* @dev Notifies the controller about an approval allowing the controller to react if desired
* Initialization check is implicitly provided by `onlyToken()`.
* @return False if the controller does not authorize the approval
*/
function onApprove(address, address, uint) external onlyToken returns (bool) {
return true;
}
/**
* @dev Called when ether is sent to the MiniMe Token contract
* Initialization check is implicitly provided by `onlyToken()`.
* @return True if the ether is accepted, false for it to throw
*/
function proxyPayment(address) external payable onlyToken returns (bool) {
return false;
}
// Forwarding fns
function isForwarder() external pure returns (bool) {
return true;
}
/**
* @notice Execute desired action as a token holder
* @dev IForwarder interface conformance. Forwards any token holder action.
* @param _evmScript Script being executed
*/
function forward(bytes _evmScript) public {
require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD);
bytes memory input = new bytes(0); // TODO: Consider input for this
// Add the managed token to the blacklist to disallow a token holder from executing actions
// on the token controller's (this contract) behalf
address[] memory blacklist = new address[](1);
blacklist[0] = address(token);
runScript(_evmScript, input, blacklist);
}
function canForward(address _sender, bytes) public view returns (bool) {
return hasInitialized() && token.balanceOf(_sender) > 0;
}
// Getter fns
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
uint64 start,
uint64 cliff,
uint64 vesting,
bool revokable
)
{
TokenVesting storage tokenVesting = vestings[_recipient][_vestingId];
amount = tokenVesting.amount;
start = tokenVesting.start;
cliff = tokenVesting.cliff;
vesting = tokenVesting.vesting;
revokable = tokenVesting.revokable;
}
function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, getTimestamp());
}
function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) {
return _transferableBalance(_holder, _time);
}
/**
* @dev Disable recovery escape hatch for own token,
* as the it has the concept of issuing tokens without assigning them
*/
function allowRecoverability(address _token) public view returns (bool) {
return _token != address(token);
}
// Internal fns
function _assign(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
// Must use transferFrom() as transfer() does not give the token controller full control
require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED);
}
function _mint(address _receiver, uint256 _amount) internal {
require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED);
token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false
}
function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) {
// Max balance doesn't apply to the token manager itself
if (_receiver == address(this)) {
return true;
}
return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens;
}
/**
* @dev Calculate amount of non-vested tokens at a specifc time
* @param tokens The total amount of tokens vested
* @param time The time at which to check
* @param start The date vesting started
* @param cliff The cliff period
* @param vested The fully vested date
* @return The amount of non-vested tokens of a specific grant
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Cliff Vested
*/
function _calculateNonVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vested
)
private
pure
returns (uint256)
{
// Shortcuts for before cliff and after vested cases.
if (time >= vested) {
return 0;
}
if (time < cliff) {
return tokens;
}
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vested - start)
// In assignVesting we enforce start <= cliff <= vested
// Here we shortcut time >= vested and time < cliff,
// so no division by 0 is possible
uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start);
// tokens - vestedTokens
return tokens.sub(vestedTokens);
}
function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) {
uint256 transferable = token.balanceOf(_holder);
// This check is not strictly necessary for the current version of this contract, as
// Token Managers now cannot assign vestings to themselves.
// However, this was a possibility in the past, so in case there were vestings assigned to
// themselves, this will still return the correct value (entire balance, as the Token
// Manager does not have a spending limit on its own balance).
if (_holder != address(this)) {
uint256 vestingsCount = vestingsLengths[_holder];
for (uint256 i = 0; i < vestingsCount; i++) {
TokenVesting storage v = vestings[_holder][i];
uint256 nonTransferable = _calculateNonVestedTokens(
v.amount,
_time,
v.start,
v.cliff,
v.vesting
);
transferable = transferable.sub(nonTransferable);
}
}
return transferable;
}
}
// File: @aragon/apps-survey/contracts/Survey.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
contract Survey is AragonApp {
using SafeMath for uint256;
using SafeMath64 for uint64;
bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE");
bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE");
uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18
uint256 public constant ABSTAIN_VOTE = 0;
string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION";
string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY";
string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER";
string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE";
string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT";
string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION";
string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE";
string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED";
string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION";
struct OptionCast {
uint256 optionId;
uint256 stake;
}
/* Allows for multiple option votes.
* Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the
* contract.
*/
struct MultiOptionVote {
uint256 optionsCastedLength;
// `castedVotes` simulates an array
// Each OptionCast in `castedVotes` must be ordered by ascending option IDs
mapping (uint256 => OptionCast) castedVotes;
}
struct SurveyStruct {
uint64 startDate;
uint64 snapshotBlock;
uint64 minParticipationPct;
uint256 options;
uint256 votingPower; // total tokens that can cast a vote
uint256 participation; // tokens that casted a vote
// Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0
mapping (uint256 => uint256) optionPower; // option ID -> voting power for option
mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes
}
MiniMeToken public token;
uint64 public minParticipationPct;
uint64 public surveyTime;
// We are mimicing an array, we use a mapping instead to make app upgrade more graceful
mapping (uint256 => SurveyStruct) internal surveys;
uint256 public surveysLength;
event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata);
event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower);
event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower);
event ChangeMinParticipation(uint64 minParticipationPct);
modifier acceptableMinParticipationPct(uint64 _minParticipationPct) {
require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION);
_;
}
modifier surveyExists(uint256 _surveyId) {
require(_surveyId < surveysLength, ERROR_NO_SURVEY);
_;
}
/**
* @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)`
* @param _token MiniMeToken address that will be used as governance token
* @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%)
* @param _surveyTime Seconds that a survey will be open for token holders to vote
*/
function initialize(
MiniMeToken _token,
uint64 _minParticipationPct,
uint64 _surveyTime
)
external
onlyInit
acceptableMinParticipationPct(_minParticipationPct)
{
initialized();
token = _token;
minParticipationPct = _minParticipationPct;
surveyTime = _surveyTime;
}
/**
* @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`%
* @param _minParticipationPct New acceptance participation
*/
function changeMinAcceptParticipationPct(uint64 _minParticipationPct)
external
authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct)))
acceptableMinParticipationPct(_minParticipationPct)
{
minParticipationPct = _minParticipationPct;
emit ChangeMinParticipation(_minParticipationPct);
}
/**
* @notice Create a new non-binding survey about "`_metadata`"
* @param _metadata Survey metadata
* @param _options Number of options voters can decide between
* @return surveyId id for newly created survey
*/
function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) {
uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block
uint256 votingPower = token.totalSupplyAt(snapshotBlock);
require(votingPower > 0, ERROR_NO_VOTING_POWER);
surveyId = surveysLength++;
SurveyStruct storage survey = surveys[surveyId];
survey.startDate = getTimestamp64();
survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block
survey.minParticipationPct = minParticipationPct;
survey.options = _options;
survey.votingPower = votingPower;
emit StartSurvey(surveyId, msg.sender, _metadata);
}
/**
* @notice Reset previously casted vote in survey #`_surveyId`, if any.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
*/
function resetVote(uint256 _surveyId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_resetVote(_surveyId);
}
/**
* @notice Vote for multiple options in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @param _surveyId Id for survey
* @param _optionIds Array with indexes of supported options
* @param _stakes Number of tokens assigned to each option
*/
function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes)
external
surveyExists(_surveyId)
{
require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT);
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
_voteOptions(_surveyId, _optionIds, _stakes);
}
/**
* @notice Vote option #`_optionId` in survey #`_surveyId`.
* @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only
* be created via `newSurvey(),` which requires initialization
* @dev It will use the whole balance.
* @param _surveyId Id for survey
* @param _optionId Index of supported option
*/
function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) {
require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE);
SurveyStruct storage survey = surveys[_surveyId];
// This could re-enter, though we can asume the governance token is not maliciuous
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256[] memory options = new uint256[](1);
uint256[] memory stakes = new uint256[](1);
options[0] = _optionId;
stakes[0] = voterStake;
_voteOptions(_surveyId, options, stakes);
}
// Getter fns
function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0;
}
function getSurvey(uint256 _surveyId)
public
view
surveyExists(_surveyId)
returns (
bool open,
uint64 startDate,
uint64 snapshotBlock,
uint64 minParticipation,
uint256 votingPower,
uint256 participation,
uint256 options
)
{
SurveyStruct storage survey = surveys[_surveyId];
open = _isSurveyOpen(survey);
startDate = survey.startDate;
snapshotBlock = survey.snapshotBlock;
minParticipation = survey.minParticipationPct;
votingPower = survey.votingPower;
participation = survey.participation;
options = survey.options;
}
/**
* @dev This is not meant to be used on-chain
*/
/* solium-disable-next-line function-order */
function getVoterState(uint256 _surveyId, address _voter)
external
view
surveyExists(_surveyId)
returns (uint256[] options, uint256[] stakes)
{
MultiOptionVote storage vote = surveys[_surveyId].votes[_voter];
if (vote.optionsCastedLength == 0) {
return (new uint256[](0), new uint256[](0));
}
options = new uint256[](vote.optionsCastedLength + 1);
stakes = new uint256[](vote.optionsCastedLength + 1);
for (uint256 i = 0; i <= vote.optionsCastedLength; i++) {
options[i] = vote.castedVotes[i].optionId;
stakes[i] = vote.castedVotes[i].stake;
}
}
function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) {
SurveyStruct storage survey = surveys[_surveyId];
require(_optionId <= survey.options, ERROR_NO_OPTION);
return survey.optionPower[_optionId];
}
function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) {
SurveyStruct storage survey = surveys[_surveyId];
// votingPower is always > 0
uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower;
return participationPct >= survey.minParticipationPct;
}
// Internal fns
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _resetVote(uint256 _surveyId) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage previousVote = survey.votes[msg.sender];
if (previousVote.optionsCastedLength > 0) {
// Voter removes their vote (index 0 is the abstain vote)
for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) {
OptionCast storage previousOptionCast = previousVote.castedVotes[i];
uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId];
uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake);
survey.optionPower[previousOptionCast.optionId] = currentOptionPower;
emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower);
}
// Compute previously casted votes (i.e. substract non-used tokens from stake)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake);
// And remove it from total participation
survey.participation = survey.participation.sub(previousParticipation);
// Reset previously voted options
delete survey.votes[msg.sender];
}
}
/*
* @dev Assumes the survey exists and that msg.sender can vote
*/
function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal {
SurveyStruct storage survey = surveys[_surveyId];
MultiOptionVote storage senderVotes = survey.votes[msg.sender];
// Revert previous votes, if any
_resetVote(_surveyId);
uint256 totalVoted = 0;
// Reserve first index for ABSTAIN_VOTE
senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 });
for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) {
// Voters don't specify that they're abstaining,
// but we still keep track of this by reserving the first index of a survey's votes.
// We subtract 1 from the indexes of the arrays passed in by the voter to account for this.
uint256 optionId = _optionIds[optionIndex - 1];
uint256 stake = _stakes[optionIndex - 1];
require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION);
require(stake > 0, ERROR_NO_STAKE);
// Let's avoid repeating an option by making sure that ascending order is preserved in
// the options array by checking that the current optionId is larger than the last one
// we added
require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED);
// Register voter amount
senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake });
// Add to total option support
survey.optionPower[optionId] = survey.optionPower[optionId].add(stake);
// Keep track of stake used so far
totalVoted = totalVoted.add(stake);
emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]);
}
// Compute and register non used tokens
// Implictly we are doing require(totalVoted <= voterStake) too
// (as stated before, index 0 is for ABSTAIN_VOTE option)
uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock);
senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted);
// Register number of options voted
senderVotes.optionsCastedLength = _optionIds.length;
// Add voter tokens to participation
survey.participation = survey.participation.add(totalVoted);
assert(survey.participation <= survey.votingPower);
}
function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) {
return getTimestamp64() < _survey.startDate.add(surveyTime);
}
}
// File: @aragon/os/contracts/acl/IACLOracle.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACLOracle {
function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool);
}
// File: @aragon/os/contracts/acl/ACL.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE");
*/
bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a;
enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types
struct Param {
uint8 id;
uint8 op;
uint240 value; // even though value is an uint240 it can store addresses
// in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal
// op and id take less than 1 byte each so it can be kept in 1 sstore
}
uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200;
uint8 internal constant TIMESTAMP_PARAM_ID = 201;
// 202 is unused
uint8 internal constant ORACLE_PARAM_ID = 203;
uint8 internal constant LOGIC_OP_PARAM_ID = 204;
uint8 internal constant PARAM_VALUE_PARAM_ID = 205;
// TODO: Add execution times param type?
/* Hardcoded constant to save gas
bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0));
*/
bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563;
bytes32 public constant NO_PERMISSION = bytes32(0);
address public constant ANY_ENTITY = address(-1);
address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager"
uint256 internal constant ORACLE_CHECK_GAS = 30000;
string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL";
string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER";
string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER";
// Whether someone has a permission
mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash
mapping (bytes32 => Param[]) internal permissionParams; // params hash => params
// Who is the manager of a permission
mapping (bytes32 => address) internal permissionManager;
event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed);
event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash);
event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager);
modifier onlyPermissionManager(address _app, bytes32 _role) {
require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER);
_;
}
modifier noPermissionManager(address _app, bytes32 _role) {
// only allow permission creation (or re-creation) when there is no manager
require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER);
_;
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(address _permissionsCreator) public onlyInit {
initialized();
require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL);
_createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator);
}
/**
* @dev Creates a permission that wasn't previously set and managed.
* If a created permission is removed it is possible to reset it with createPermission.
* This is the **ONLY** way to create permissions and set managers to permissions that don't
* have a manager.
* In terms of the ACL being initialized, this function implicitly protects all the other
* state-changing external functions, as they all require the sender to be a manager.
* @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _manager Address of the entity that will be able to grant and revoke the permission further.
*/
function createPermission(address _entity, address _app, bytes32 _role, address _manager)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_createPermission(_entity, _app, _role, _manager);
}
/**
* @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
*/
function grantPermission(address _entity, address _app, bytes32 _role)
external
{
grantPermissionP(_entity, _app, _role, new uint256[](0));
}
/**
* @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager
* @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)
* @param _role Identifier for the group of actions in app given access to perform
* @param _params Permission parameters
*/
function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params)
public
onlyPermissionManager(_app, _role)
{
bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH;
_setPermission(_entity, _app, _role, paramsHash);
}
/**
* @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager
* @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app`
* @param _entity Address of the whitelisted entity to revoke access from
* @param _app Address of the app in which the role will be revoked
* @param _role Identifier for the group of actions in app being revoked
*/
function revokePermission(address _entity, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermission(_entity, _app, _role, NO_PERMISSION);
}
/**
* @notice Set `_newManager` as the manager of `_role` in `_app`
* @param _newManager Address for the new manager
* @param _app Address of the app in which the permission management is being transferred
* @param _role Identifier for the group of actions being transferred
*/
function setPermissionManager(address _newManager, address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(_newManager, _app, _role);
}
/**
* @notice Remove the manager of `_role` in `_app`
* @param _app Address of the app in which the permission is being unmanaged
* @param _role Identifier for the group of actions being unmanaged
*/
function removePermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(address(0), _app, _role);
}
/**
* @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function createBurnedPermission(address _app, bytes32 _role)
external
auth(CREATE_PERMISSIONS_ROLE)
noPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager)
* @param _app Address of the app in which the permission is being burned
* @param _role Identifier for the group of actions being burned
*/
function burnPermissionManager(address _app, bytes32 _role)
external
onlyPermissionManager(_app, _role)
{
_setPermissionManager(BURN_ENTITY, _app, _role);
}
/**
* @notice Get parameters for permission array length
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return Length of the array
*/
function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) {
return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length;
}
/**
* @notice Get parameter for permission
* @param _entity Address of the whitelisted entity that will be able to perform the role
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @param _index Index of parameter in the array
* @return Parameter (id, op, value)
*/
function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index)
external
view
returns (uint8, uint8, uint240)
{
Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index];
return (param.id, param.op, param.value);
}
/**
* @dev Get manager for permission
* @param _app Address of the app
* @param _role Identifier for a group of actions in app
* @return address of the manager for the permission
*/
function getPermissionManager(address _app, bytes32 _role) public view returns (address) {
return permissionManager[roleHash(_app, _role)];
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission statu
* @param _who Sender of the original call
* @param _where Address of the app
* @param _where Identifier for a group of actions in app
* @param _how Permission parameters
* @return boolean indicating whether the ACL allows the role or not
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) {
return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how));
}
function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) {
bytes32 whoParams = permissions[permissionHash(_who, _where, _what)];
if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) {
return true;
}
bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)];
if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) {
return true;
}
return false;
}
function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) {
uint256[] memory empty = new uint256[](0);
return hasPermission(_who, _where, _what, empty);
}
function evalParams(
bytes32 _paramsHash,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) public view returns (bool)
{
if (_paramsHash == EMPTY_PARAM_HASH) {
return true;
}
return _evalParam(_paramsHash, 0, _who, _where, _what, _how);
}
/**
* @dev Internal createPermission for access inside the kernel (on instantiation)
*/
function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal {
_setPermission(_entity, _app, _role, EMPTY_PARAM_HASH);
_setPermissionManager(_manager, _app, _role);
}
/**
* @dev Internal function called to actually save the permission
*/
function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal {
permissions[permissionHash(_entity, _app, _role)] = _paramsHash;
bool entityHasPermission = _paramsHash != NO_PERMISSION;
bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH;
emit SetPermission(_entity, _app, _role, entityHasPermission);
if (permissionHasParams) {
emit SetPermissionParams(_entity, _app, _role, _paramsHash);
}
}
function _saveParams(uint256[] _encodedParams) internal returns (bytes32) {
bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams));
Param[] storage params = permissionParams[paramHash];
if (params.length == 0) { // params not saved before
for (uint256 i = 0; i < _encodedParams.length; i++) {
uint256 encodedParam = _encodedParams[i];
Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam));
params.push(param);
}
}
return paramHash;
}
function _evalParam(
bytes32 _paramsHash,
uint32 _paramId,
address _who,
address _where,
bytes32 _what,
uint256[] _how
) internal view returns (bool)
{
if (_paramId >= permissionParams[_paramsHash].length) {
return false; // out of bounds
}
Param memory param = permissionParams[_paramsHash][_paramId];
if (param.id == LOGIC_OP_PARAM_ID) {
return _evalLogic(param, _paramsHash, _who, _where, _what, _how);
}
uint256 value;
uint256 comparedTo = uint256(param.value);
// get value
if (param.id == ORACLE_PARAM_ID) {
value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0;
comparedTo = 1;
} else if (param.id == BLOCK_NUMBER_PARAM_ID) {
value = getBlockNumber();
} else if (param.id == TIMESTAMP_PARAM_ID) {
value = getTimestamp();
} else if (param.id == PARAM_VALUE_PARAM_ID) {
value = uint256(param.value);
} else {
if (param.id >= _how.length) {
return false;
}
value = uint256(uint240(_how[param.id])); // force lost precision
}
if (Op(param.op) == Op.RET) {
return uint256(value) > 0;
}
return compare(value, Op(param.op), comparedTo);
}
function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how)
internal
view
returns (bool)
{
if (Op(_param.op) == Op.IF_ELSE) {
uint32 conditionParam;
uint32 successParam;
uint32 failureParam;
(conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value));
bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how);
return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how);
}
uint32 param1;
uint32 param2;
(param1, param2,) = decodeParamsList(uint256(_param.value));
bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how);
if (Op(_param.op) == Op.NOT) {
return !r1;
}
if (r1 && Op(_param.op) == Op.OR) {
return true;
}
if (!r1 && Op(_param.op) == Op.AND) {
return false;
}
bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how);
if (Op(_param.op) == Op.XOR) {
return r1 != r2;
}
return r2; // both or and and depend on result of r2 after checks
}
function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) {
if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace
if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace
if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace
if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace
if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace
if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace
return false;
}
function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) {
bytes4 sig = _oracleAddr.canPerform.selector;
// a raw call is required so we can return false if the call reverts, rather than reverting
bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how);
uint256 oracleCheckGas = ORACLE_CHECK_GAS;
bool ok;
assembly {
ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0)
}
if (!ok) {
return false;
}
uint256 size;
assembly { size := returndatasize }
if (size != 32) {
return false;
}
bool result;
assembly {
let ptr := mload(0x40) // get next free memory ptr
returndatacopy(ptr, 0, size) // copy return from above `staticcall`
result := mload(ptr) // read data at ptr and set it to result
mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr
}
return result;
}
/**
* @dev Internal function that sets management
*/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal {
permissionManager[roleHash(_app, _role)] = _newManager;
emit ChangePermissionManager(_app, _role, _newManager);
}
function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("ROLE", _where, _what));
}
function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what));
}
}
// File: @aragon/os/contracts/apm/Repo.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract Repo is AragonApp {
/* Hardcoded constants to save gas
bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE");
*/
bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8;
string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP";
string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION";
string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION";
struct Version {
uint16[3] semanticVersion;
address contractAddress;
bytes contentURI;
}
uint256 internal versionsNextIndex;
mapping (uint256 => Version) internal versions;
mapping (bytes32 => uint256) internal versionIdForSemantic;
mapping (address => uint256) internal latestVersionIdForContract;
event NewVersion(uint256 versionId, uint16[3] semanticVersion);
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this Repo
*/
function initialize() public onlyInit {
initialized();
versionsNextIndex = 1;
}
/**
* @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)`
* @param _newSemanticVersion Semantic version for new repo version
* @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
* @param _contentURI External URI for fetching new version's content
*/
function newVersion(
uint16[3] _newSemanticVersion,
address _contractAddress,
bytes _contentURI
) public auth(CREATE_VERSION_ROLE)
{
address contractAddress = _contractAddress;
uint256 lastVersionIndex = versionsNextIndex - 1;
uint16[3] memory lastSematicVersion;
if (lastVersionIndex > 0) {
Version storage lastVersion = versions[lastVersionIndex];
lastSematicVersion = lastVersion.semanticVersion;
if (contractAddress == address(0)) {
contractAddress = lastVersion.contractAddress;
}
// Only allows smart contract change on major version bumps
require(
lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
ERROR_INVALID_VERSION
);
}
require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);
uint256 versionId = versionsNextIndex++;
versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
latestVersionIdForContract[contractAddress] = versionId;
emit NewVersion(versionId, _newSemanticVersion);
}
function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
return getByVersionId(versionsNextIndex - 1);
}
function getLatestForContractAddress(address _contractAddress)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(latestVersionIdForContract[_contractAddress]);
}
function getBySemanticVersion(uint16[3] _semanticVersion)
public
view
returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI)
{
return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]);
}
function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) {
require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION);
Version storage version = versions[_versionId];
return (version.semanticVersion, version.contractAddress, version.contentURI);
}
function getVersionsCount() public view returns (uint256) {
return versionsNextIndex - 1;
}
function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) {
bool hasBumped;
uint i = 0;
while (i < 3) {
if (hasBumped) {
if (_newVersion[i] != 0) {
return false;
}
} else if (_newVersion[i] != _oldVersion[i]) {
if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) {
return false;
}
hasBumped = true;
}
i++;
}
return hasBumped;
}
function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(version[0], version[1], version[2]));
}
}
// File: @aragon/os/contracts/apm/APMNamehash.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract APMNamehash {
/* Hardcoded constants to save gas
bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm"))));
*/
bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba;
function apmNamehash(string name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name))));
}
}
// File: @aragon/os/contracts/kernel/KernelStorage.sol
pragma solidity 0.4.24;
contract KernelStorage {
// namespace => app id => address
mapping (bytes32 => mapping (bytes32 => address)) public apps;
bytes32 public recoveryVaultAppId;
}
// File: @aragon/os/contracts/lib/misc/ERCProxy.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ERCProxy {
uint256 internal constant FORWARDING = 1;
uint256 internal constant UPGRADEABLE = 2;
function proxyType() public pure returns (uint256 proxyTypeId);
function implementation() public view returns (address codeAddr);
}
// File: @aragon/os/contracts/common/DelegateProxy.sol
pragma solidity 0.4.24;
contract DelegateProxy is ERCProxy, IsContract {
uint256 internal constant FWD_GAS_LIMIT = 10000;
/**
* @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
* @param _dst Destination address to perform the delegatecall
* @param _calldata Calldata for the delegatecall
*/
function delegatedFwd(address _dst, bytes _calldata) internal {
require(isContract(_dst));
uint256 fwdGasLimit = FWD_GAS_LIMIT;
assembly {
let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
// revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
// if the call returned error data, forward it
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File: @aragon/os/contracts/common/DepositableDelegateProxy.sol
pragma solidity 0.4.24;
contract DepositableDelegateProxy is DepositableStorage, DelegateProxy {
event ProxyDeposit(address sender, uint256 value);
function () external payable {
// send / transfer
if (gasleft() < FWD_GAS_LIMIT) {
require(msg.value > 0 && msg.data.length == 0);
require(isDepositable());
emit ProxyDeposit(msg.sender, msg.value);
} else { // all calls except for send or transfer
address target = implementation();
delegatedFwd(target, msg.data);
}
}
}
// File: @aragon/os/contracts/apps/AppProxyBase.sol
pragma solidity 0.4.24;
contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants {
/**
* @dev Initialize AppProxy
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public {
setKernel(_kernel);
setAppId(_appId);
// Implicit check that kernel is actually a Kernel
// The EVM doesn't actually provide a way for us to make sure, but we can force a revert to
// occur if the kernel is set to 0x0 or a non-code address when we try to call a method on
// it.
address appCode = getAppBase(_appId);
// If initialize payload is provided, it will be executed
if (_initializePayload.length > 0) {
require(isContract(appCode));
// Cannot make delegatecall as a delegateproxy.delegatedFwd as it
// returns ending execution context and halts contract deployment
require(appCode.delegatecall(_initializePayload));
}
}
function getAppBase(bytes32 _appId) internal view returns (address) {
return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId);
}
}
// File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol
pragma solidity 0.4.24;
contract AppProxyUpgradeable is AppProxyBase {
/**
* @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
// solium-disable-previous-line no-empty-blocks
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return getAppBase(appId());
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
}
// File: @aragon/os/contracts/apps/AppProxyPinned.sol
pragma solidity 0.4.24;
contract AppProxyPinned is IsContract, AppProxyBase {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.appStorage.pinnedCode")
bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e;
/**
* @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app)
* @param _kernel Reference to organization kernel for the app
* @param _appId Identifier for app
* @param _initializePayload Payload for call to be made after setup to initialize
*/
constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload)
AppProxyBase(_kernel, _appId, _initializePayload)
public // solium-disable-line visibility-first
{
setPinnedCode(getAppBase(_appId));
require(isContract(pinnedCode()));
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return pinnedCode();
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return FORWARDING;
}
function setPinnedCode(address _pinnedCode) internal {
PINNED_CODE_POSITION.setStorageAddress(_pinnedCode);
}
function pinnedCode() internal view returns (address) {
return PINNED_CODE_POSITION.getStorageAddress();
}
}
// File: @aragon/os/contracts/factory/AppProxyFactory.sol
pragma solidity 0.4.24;
contract AppProxyFactory {
event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId);
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) {
return newAppProxy(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyUpgradeable
*/
function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) {
AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), true, _appId);
return proxy;
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) {
return newAppProxyPinned(_kernel, _appId, new bytes(0));
}
/**
* @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload`
* @param _kernel App's Kernel reference
* @param _appId Identifier for app
* @param _initializePayload Proxy initialization payload
* @return AppProxyPinned
*/
function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) {
AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload);
emit NewAppProxy(address(proxy), false, _appId);
return proxy;
}
}
// File: @aragon/os/contracts/kernel/Kernel.sol
pragma solidity 0.4.24;
// solium-disable-next-line max-len
contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar {
/* Hardcoded constants to save gas
bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE");
*/
bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0;
string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT";
string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE";
string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED";
/**
* @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately.
* @param _shouldPetrify Immediately petrify this instance so that it can never be initialized
*/
constructor(bool _shouldPetrify) public {
if (_shouldPetrify) {
petrify();
}
}
/**
* @dev Initialize can only be called once. It saves the block number in which it was initialized.
* @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions
* @param _baseAcl Address of base ACL app
* @param _permissionsCreator Entity that will be given permission over createPermission
*/
function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit {
initialized();
// Set ACL base
_setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl);
// Create ACL instance and attach it as the default ACL app
IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID));
acl.initialize(_permissionsCreator);
_setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl);
recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID;
}
/**
* @dev Create a new instance of an app linked to this kernel
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new instance of an app linked to this kernel and set its base
* implementation if it was not already set
* @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxy(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Create a new pinned instance of an app linked to this kernel
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`.
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
return newPinnedAppInstance(_appId, _appBase, new bytes(0), false);
}
/**
* @dev Create a new pinned instance of an app linked to this kernel and set
* its base implementation if it was not already set
* @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''`
* @param _appId Identifier for app
* @param _appBase Address of the app's base implementation
* @param _initializePayload Payload for call made by the proxy during its construction to initialize
* @param _setDefault Whether the app proxy app is the default one.
* Useful when the Kernel needs to know of an instance of a particular app,
* like Vault for escape hatch mechanism.
* @return AppProxy instance
*/
function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
{
_setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase);
appProxy = newAppProxyPinned(this, _appId, _initializePayload);
// By calling setApp directly and not the internal functions, we make sure the params are checked
// and it will only succeed if sender has permissions to set something to the namespace.
if (_setDefault) {
setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy);
}
}
/**
* @dev Set the resolving address of an app instance or base implementation
* @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app`
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @param _app Address of the app instance or base implementation
* @return ID of app
*/
function setApp(bytes32 _namespace, bytes32 _appId, address _app)
public
auth(APP_MANAGER_ROLE, arr(_namespace, _appId))
{
_setApp(_namespace, _appId, _app);
}
/**
* @dev Set the default vault id for the escape hatch mechanism
* @param _recoveryVaultAppId Identifier of the recovery vault app
*/
function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId))
{
recoveryVaultAppId = _recoveryVaultAppId;
}
// External access to default app id and namespace constants to mimic default getters for constants
/* solium-disable function-order, mixedcase */
function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; }
function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; }
function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; }
function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; }
function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; }
/* solium-enable function-order, mixedcase */
/**
* @dev Get the address of an app instance or base implementation
* @param _namespace App namespace to use
* @param _appId Identifier for app
* @return Address of the app
*/
function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) {
return apps[_namespace][_appId];
}
/**
* @dev Get the address of the recovery Vault instance (to recover funds)
* @return Address of the Vault
*/
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
/**
* @dev Get the installed ACL app
* @return ACL app
*/
function acl() public view returns (IACL) {
return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID));
}
/**
* @dev Function called by apps to check ACL on kernel or to check permission status
* @param _who Sender of the original call
* @param _where Address of the app
* @param _what Identifier for a group of actions in app
* @param _how Extra data for ACL auth
* @return Boolean indicating whether the ACL allows the role or not.
* Always returns false if the kernel hasn't been initialized yet.
*/
function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) {
IACL defaultAcl = acl();
return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas)
defaultAcl.hasPermission(_who, _where, _what, _how);
}
function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal {
require(isContract(_app), ERROR_APP_NOT_CONTRACT);
apps[_namespace][_appId] = _app;
emit SetApp(_namespace, _appId, _app);
}
function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal {
address app = getApp(_namespace, _appId);
if (app != address(0)) {
// The only way to set an app is if it passes the isContract check, so no need to check it again
require(app == _app, ERROR_INVALID_APP_CHANGE);
} else {
_setApp(_namespace, _appId, _app);
}
}
modifier auth(bytes32 _role, uint256[] memory _params) {
require(
hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)),
ERROR_AUTH_FAILED
);
_;
}
}
// File: @aragon/os/contracts/lib/ens/AbstractENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol
pragma solidity ^0.4.15;
interface AbstractENS {
function owner(bytes32 _node) public constant returns (address);
function resolver(bytes32 _node) public constant returns (address);
function ttl(bytes32 _node) public constant returns (uint64);
function setOwner(bytes32 _node, address _owner) public;
function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public;
function setResolver(bytes32 _node, address _resolver) public;
function setTTL(bytes32 _node, uint64 _ttl) public;
// 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);
}
// File: @aragon/os/contracts/lib/ens/ENS.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol
pragma solidity ^0.4.0;
/**
* The ENS registry contract.
*/
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() public {
records[0].owner = msg.sender;
}
/**
* Returns the address that owns the specified node.
*/
function owner(bytes32 node) public constant returns (address) {
return records[node].owner;
}
/**
* Returns the address of the resolver for the specified node.
*/
function resolver(bytes32 node) public constant returns (address) {
return records[node].resolver;
}
/**
* Returns the TTL of a node, and any records associated with it.
*/
function ttl(bytes32 node) public 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) public {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* Transfers ownership of a subnode keccak256(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) public {
var subnode = keccak256(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) public {
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) public {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
}
// File: @aragon/os/contracts/lib/ens/PublicResolver.sol
// See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol
pragma solidity ^0.4.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
}
AbstractENS ens;
mapping(bytes32=>Record) records;
modifier only_owner(bytes32 node) {
if (ens.owner(node) != msg.sender) throw;
_;
}
/**
* Constructor.
* @param ensAddr The ENS registrar contract.
*/
function PublicResolver(AbstractENS ensAddr) public {
ens = ensAddr;
}
/**
* Returns true if the resolver implements the interface specified by the provided hash.
* @param interfaceID The ID of the interface to check for.
* @return True if the contract implements the requested interface.
*/
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public constant returns (address ret) {
ret = records[node].addr;
}
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) only_owner(node) public {
records[node].addr = addr;
AddrChanged(node, addr);
}
/**
* Returns the content hash associated with an ENS node.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The ENS node to query.
* @return The associated content hash.
*/
function content(bytes32 node) public constant returns (bytes32 ret) {
ret = records[node].content;
}
/**
* Sets the content hash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* Note that this resource type is not standardized, and will likely change
* in future to a resource type based on multihash.
* @param node The node to update.
* @param hash The content hash to set
*/
function setContent(bytes32 node, bytes32 hash) only_owner(node) public {
records[node].content = hash;
ContentChanged(node, hash);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) public constant returns (string ret) {
ret = records[node].name;
}
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string name) only_owner(node) public {
records[node].name = name;
NameChanged(node, name);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) {
var record = records[node];
for(contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public {
// Content types must be powers of 2
if (((contentType - 1) & contentType) != 0) throw;
records[node].abis[contentType] = data;
ABIChanged(node, contentType);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public {
records[node].pubkey = PublicKey(x, y);
PubkeyChanged(node, x, y);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string key) public constant returns (string ret) {
ret = records[node].text[key];
}
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string key, string value) only_owner(node) public {
records[node].text[key] = value;
TextChanged(node, key, key);
}
}
// File: @aragon/os/contracts/kernel/KernelProxy.sol
pragma solidity 0.4.24;
contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy {
/**
* @dev KernelProxy is a proxy contract to a kernel implementation. The implementation
* can update the reference, which effectively upgrades the contract
* @param _kernelImpl Address of the contract used as implementation for kernel
*/
constructor(IKernel _kernelImpl) public {
require(isContract(address(_kernelImpl)));
apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl;
// Note that emitting this event is important for verifying that a KernelProxy instance
// was never upgraded to a malicious Kernel logic contract over its lifespan.
// This starts the "chain of trust", that can be followed through later SetApp() events
// emitted during kernel upgrades.
emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl);
}
/**
* @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy
*/
function proxyType() public pure returns (uint256 proxyTypeId) {
return UPGRADEABLE;
}
/**
* @dev ERC897, the address the proxy would delegate calls to
*/
function implementation() public view returns (address) {
return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID];
}
}
// File: @aragon/os/contracts/evmscript/ScriptHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library ScriptHelpers {
function getSpecId(bytes _script) internal pure returns (uint32) {
return uint32At(_script, 0);
}
function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := mload(add(_data, add(0x20, _location)))
}
}
function addressAt(bytes _data, uint256 _location) internal pure returns (address result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000),
0x1000000000000000000000000)
}
}
function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) {
uint256 word = uint256At(_data, _location);
assembly {
result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000),
0x100000000000000000000000000000000000000000000000000000000)
}
}
function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) {
assembly {
result := add(_data, add(0x20, _location))
}
}
function toBytes(bytes4 _sig) internal pure returns (bytes) {
bytes memory payload = new bytes(4);
assembly { mstore(add(payload, 0x20), _sig) }
return payload;
}
}
// File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol
pragma solidity 0.4.24;
/* solium-disable function-order */
// Allow public initialize() to be first
contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE");
bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE");
*/
bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2;
// WARN: Manager can censor all votes and the like happening in an org
bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3;
uint256 internal constant SCRIPT_START_LOCATION = 4;
string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR";
string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED";
string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED";
string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT";
struct ExecutorEntry {
IEVMScriptExecutor executor;
bool enabled;
}
uint256 private executorsNextIndex;
mapping (uint256 => ExecutorEntry) public executors;
event EnableExecutor(uint256 indexed executorId, address indexed executorAddress);
event DisableExecutor(uint256 indexed executorId, address indexed executorAddress);
modifier executorExists(uint256 _executorId) {
require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR);
_;
}
/**
* @notice Initialize the registry
*/
function initialize() public onlyInit {
initialized();
// Create empty record to begin executor IDs at 1
executorsNextIndex = 1;
}
/**
* @notice Add a new script executor with address `_executor` to the registry
* @param _executor Address of the IEVMScriptExecutor that will be added to the registry
* @return id Identifier of the executor in the registry
*/
function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) {
uint256 executorId = executorsNextIndex++;
executors[executorId] = ExecutorEntry(_executor, true);
emit EnableExecutor(executorId, _executor);
return executorId;
}
/**
* @notice Disable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function disableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
{
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage executorEntry = executors[_executorId];
require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED);
executorEntry.enabled = false;
emit DisableExecutor(_executorId, executorEntry.executor);
}
/**
* @notice Enable script executor with ID `_executorId`
* @param _executorId Identifier of the executor in the registry
*/
function enableScriptExecutor(uint256 _executorId)
external
authP(REGISTRY_MANAGER_ROLE, arr(_executorId))
executorExists(_executorId)
{
ExecutorEntry storage executorEntry = executors[_executorId];
require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED);
executorEntry.enabled = true;
emit EnableExecutor(_executorId, executorEntry.executor);
}
/**
* @dev Get the script executor that can execute a particular script based on its first 4 bytes
* @param _script EVMScript being inspected
*/
function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT);
uint256 id = _script.getSpecId();
// Note that we don't need to check for an executor's existence in this case, as only
// existing executors can be enabled
ExecutorEntry storage entry = executors[id];
return entry.enabled ? entry.executor : IEVMScriptExecutor(0);
}
}
// File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified {
uint256 internal constant SCRIPT_START_LOCATION = 4;
}
// File: @aragon/os/contracts/evmscript/executors/CallsScript.sol
pragma solidity 0.4.24;
// Inspired by https://github.com/reverendus/tx-manager
contract CallsScript is BaseEVMScriptExecutor {
using ScriptHelpers for bytes;
/* Hardcoded constants to save gas
bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT");
*/
bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302;
string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL";
string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH";
/* This is manually crafted in assembly
string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED";
*/
event LogScriptCall(address indexed sender, address indexed src, address indexed dst);
/**
* @notice Executes a number of call scripts
* @param _script [ specId (uint32) ] many calls with this structure ->
* [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ]
* @param _blacklist Addresses the script cannot call to, or will revert.
* @return Always returns empty byte array
*/
function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) {
uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id
while (location < _script.length) {
// Check there's at least address + calldataLength available
require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH);
address contractAddress = _script.addressAt(location);
// Check address being called is not blacklist
for (uint256 i = 0; i < _blacklist.length; i++) {
require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL);
}
// logged before execution to ensure event ordering in receipt
// if failed entire execution is reverted regardless
emit LogScriptCall(msg.sender, address(this), contractAddress);
uint256 calldataLength = uint256(_script.uint32At(location + 0x14));
uint256 startOffset = location + 0x14 + 0x04;
uint256 calldataStart = _script.locationOf(startOffset);
// compute end of script / next location
location = startOffset + calldataLength;
require(location <= _script.length, ERROR_INVALID_LENGTH);
bool success;
assembly {
success := call(
sub(gas, 5000), // forward gas left - 5000
contractAddress, // address
0, // no value
calldataStart, // calldata start
calldataLength, // calldata length
0, // don't write output
0 // don't write output
)
switch success
case 0 {
let ptr := mload(0x40)
switch returndatasize
case 0 {
// No error data was returned, revert with "EVMCALLS_CALL_REVERTED"
// See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in
// this memory layout
mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length
mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason
revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Forward the full error data
returndatacopy(ptr, 0, returndatasize)
revert(ptr, returndatasize)
}
}
default { }
}
}
// No need to allocate empty bytes for the return as this can only be called via an delegatecall
// (due to the isInitialized modifier)
}
function executorType() external pure returns (bytes32) {
return EXECUTOR_TYPE;
}
}
// File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol
pragma solidity 0.4.24;
contract EVMScriptRegistryFactory is EVMScriptRegistryConstants {
EVMScriptRegistry public baseReg;
IEVMScriptExecutor public baseCallScript;
/**
* @notice Create a new EVMScriptRegistryFactory.
*/
constructor() public {
baseReg = new EVMScriptRegistry();
baseCallScript = IEVMScriptExecutor(new CallsScript());
}
/**
* @notice Install a new pinned instance of EVMScriptRegistry on `_dao`.
* @param _dao Kernel
* @return Installed EVMScriptRegistry
*/
function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) {
bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector);
reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true));
ACL acl = ACL(_dao.acl());
acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this);
reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript
// Clean up the permissions
acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE());
return reg;
}
}
// File: @aragon/os/contracts/factory/DAOFactory.sol
pragma solidity 0.4.24;
contract DAOFactory {
IKernel public baseKernel;
IACL public baseACL;
EVMScriptRegistryFactory public regFactory;
event DeployDAO(address dao);
event DeployEVMScriptRegistry(address reg);
/**
* @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`.
* @param _baseKernel Base Kernel
* @param _baseACL Base ACL
* @param _regFactory EVMScriptRegistry factory
*/
constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
/**
* @notice Create a new DAO with `_root` set as the initial admin
* @param _root Address that will be granted control to setup DAO permissions
* @return Newly created DAO
*/
function newDAO(address _root) public returns (Kernel) {
Kernel dao = Kernel(new KernelProxy(baseKernel));
if (address(regFactory) == address(0)) {
dao.initialize(baseACL, _root);
} else {
dao.initialize(baseACL, this);
ACL acl = ACL(dao.acl());
bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE();
bytes32 appManagerRole = dao.APP_MANAGER_ROLE();
acl.grantPermission(regFactory, acl, permRole);
acl.createPermission(regFactory, dao, appManagerRole, this);
EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao);
emit DeployEVMScriptRegistry(address(reg));
// Clean up permissions
// First, completely reset the APP_MANAGER_ROLE
acl.revokePermission(regFactory, dao, appManagerRole);
acl.removePermissionManager(dao, appManagerRole);
// Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE
acl.revokePermission(regFactory, acl, permRole);
acl.revokePermission(this, acl, permRole);
acl.grantPermission(_root, acl, permRole);
acl.setPermissionManager(_root, acl, permRole);
}
emit DeployDAO(address(dao));
return dao;
}
}
// File: @aragon/id/contracts/ens/IPublicResolver.sol
pragma solidity ^0.4.0;
interface IPublicResolver {
function supportsInterface(bytes4 interfaceID) constant returns (bool);
function addr(bytes32 node) constant returns (address ret);
function setAddr(bytes32 node, address addr);
function hash(bytes32 node) constant returns (bytes32 ret);
function setHash(bytes32 node, bytes32 hash);
}
// File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol
pragma solidity 0.4.24;
interface IFIFSResolvingRegistrar {
function register(bytes32 _subnode, address _owner) external;
function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public;
}
// File: @aragon/templates-shared/contracts/BaseTemplate.sol
pragma solidity 0.4.24;
contract BaseTemplate is APMNamehash, IsContract {
using Uint256Helpers for uint256;
/* Hardcoded constant to save gas
* bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth
* bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth
* bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth
* bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth
* bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth
* bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth
* bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth
*/
bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a;
bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4;
bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991;
bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae;
bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f;
bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e;
string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT";
string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT";
string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED";
string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT";
string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED";
string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT";
string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS";
string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID";
ENS internal ens;
DAOFactory internal daoFactory;
MiniMeTokenFactory internal miniMeFactory;
IFIFSResolvingRegistrar internal aragonID;
event DeployDao(address dao);
event SetupDao(address dao);
event DeployToken(address token);
event InstalledApp(address appProxy, bytes32 appId);
constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public {
require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT);
require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT);
ens = _ens;
aragonID = _aragonID;
daoFactory = _daoFactory;
miniMeFactory = _miniMeFactory;
}
/**
* @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full
* control during setup. Once the DAO setup has finished, it is recommended to call the
* `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root
* permissions to the end entity in control of the organization.
*/
function _createDAO() internal returns (Kernel dao, ACL acl) {
dao = daoFactory.newDAO(this);
emit DeployDao(address(dao));
acl = ACL(dao.acl());
_createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE());
}
/* ACL */
function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal {
_acl.createPermission(_grantees[0], _app, _permission, address(this));
for (uint256 i = 1; i < _grantees.length; i++) {
_acl.grantPermission(_grantees[i], _app, _permission);
}
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.createPermission(address(this), _app, _permission, address(this));
}
function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal {
_acl.revokePermission(address(this), _app, _permission);
_acl.removePermissionManager(_app, _permission);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal {
_transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to);
}
function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal {
ACL _acl = ACL(_dao.acl());
_transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager);
_transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager);
emit SetupDao(_dao);
}
function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal {
_acl.grantPermission(_to, _app, _permission);
_acl.revokePermission(address(this), _app, _permission);
_acl.setPermissionManager(_manager, _app, _permission);
}
/* AGENT */
function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData));
// We assume that installing the Agent app as a default app means the DAO should have its
// Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent.
_dao.setRecoveryVaultAppId(AGENT_APP_ID);
return agent;
}
function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) {
bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector);
return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData));
}
function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager);
_acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager);
}
/* VAULT */
function _installVaultApp(Kernel _dao) internal returns (Vault) {
bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector);
return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData));
}
function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager);
}
/* VOTING */
function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) {
return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]);
}
function _installVotingApp(
Kernel _dao,
MiniMeToken _token,
uint64 _support,
uint64 _acceptance,
uint64 _duration
)
internal returns (Voting)
{
bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration);
return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData));
}
function _createVotingPermissions(
ACL _acl,
Voting _voting,
address _settingsGrantee,
address _createVotesGrantee,
address _manager
)
internal
{
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager);
_acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager);
_acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager);
}
/* SURVEY */
function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) {
bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime);
return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData));
}
function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager);
_acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager);
}
/* PAYROLL */
function _installPayrollApp(
Kernel _dao,
Finance _finance,
address _denominationToken,
IFeed _priceFeed,
uint64 _rateExpiryTime
)
internal returns (Payroll)
{
bytes memory initializeData = abi.encodeWithSelector(
Payroll(0).initialize.selector,
_finance,
_denominationToken,
_priceFeed,
_rateExpiryTime
);
return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData));
}
/**
* @dev Internal function to configure payroll permissions. Note that we allow defining different managers for
* payroll since it may be useful to have one control the payroll settings (rate expiration, price feed,
* and allowed tokens), and another one to control the employee functionality (bonuses, salaries,
* reimbursements, employees, etc).
* @param _acl ACL instance being configured
* @param _acl Payroll app being configured
* @param _employeeManager Address that will receive permissions to handle employee payroll functionality
* @param _settingsManager Address that will receive permissions to manage payroll settings
* @param _permissionsManager Address that will be the ACL manager for the payroll permissions
*/
function _createPayrollPermissions(
ACL _acl,
Payroll _payroll,
address _employeeManager,
address _settingsManager,
address _permissionsManager
)
internal
{
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager);
_acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager);
_acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager);
}
function _unwrapPayrollSettings(
uint256[4] memory _payrollSettings
)
internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager)
{
denominationToken = _toAddress(_payrollSettings[0]);
priceFeed = IFeed(_toAddress(_payrollSettings[1]));
rateExpiryTime = _payrollSettings[2].toUint64();
employeeManager = _toAddress(_payrollSettings[3]);
}
/* FINANCE */
function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) {
bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration);
return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData));
}
function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager);
_acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager);
}
function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager);
}
function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal {
_acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal {
_acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE());
}
/* TOKEN MANAGER */
function _installTokenManagerApp(
Kernel _dao,
MiniMeToken _token,
bool _transferable,
uint256 _maxAccountTokens
)
internal returns (TokenManager)
{
TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID));
_token.changeController(tokenManager);
tokenManager.initialize(_token, _transferable, _maxAccountTokens);
return tokenManager;
}
function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal {
_acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager);
_acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager);
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stakes[i]);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
for (uint256 i = 0; i < _holders.length; i++) {
_tokenManager.mint(_holders[i], _stake);
}
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal {
_createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
_tokenManager.mint(_holder, _stake);
_removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE());
}
/* EVM SCRIPTS */
function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal {
EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry());
_acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager);
_acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager);
}
/* APPS */
function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installNonDefaultApp(_dao, _appId, new bytes(0));
}
function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, false);
}
function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) {
return _installDefaultApp(_dao, _appId, new bytes(0));
}
function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) {
return _installApp(_dao, _appId, _initializeData, true);
}
function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) {
address latestBaseAppAddress = _latestVersionAppBase(_appId);
address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault));
emit InstalledApp(instance, _appId);
return instance;
}
function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) {
Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId));
(,base,) = repo.getLatest();
}
/* TOKEN */
function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) {
require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED);
MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true);
emit DeployToken(address(token));
return token;
}
function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view {
require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT);
}
/* IDS */
function _validateId(string memory _id) internal pure {
require(bytes(_id).length > 0, ERROR_INVALID_ID);
}
function _registerID(string memory _name, address _owner) internal {
require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED);
aragonID.register(keccak256(abi.encodePacked(_name)), _owner);
}
function _ensureAragonIdIsValid(address _aragonID) internal view {
require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT);
}
/* HELPERS */
function _toAddress(uint256 _value) private pure returns (address) {
require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS);
return address(_value);
}
}
// File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol
pragma solidity 0.4.24;
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
// File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol
pragma solidity 0.4.24;
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
}
// File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol
pragma solidity 0.4.24;
contract BancorFormula is IBancorFormula, Utils {
using SafeMath for uint256;
string public version = '0.3';
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
Auto-generated via 'PrintIntScalingFactors.py'
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
Auto-generated via 'PrintFunctionConstructor.py'
*/
uint256[128] private maxExpArray;
constructor() public {
// maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
@dev given a token supply, connector balance, weight and a deposit amount (in the connector token),
calculates the return for a given conversion (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1)
@param _supply token total supply
@param _connectorBalance total connector balance
@param _connectorWeight connector weight, represented in ppm, 1-1000000
@param _depositAmount deposit amount, in connector token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _supply.mul(_depositAmount) / _connectorBalance;
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_connectorBalance);
(result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT);
uint256 temp = _supply.mul(result) >> precision;
return temp - _supply;
}
/**
@dev given a token supply, connector balance, weight and a sell amount (in the main token),
calculates the return for a given conversion (in the connector token)
Formula:
Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
@param _supply token total supply
@param _connectorBalance total connector
@param _connectorWeight constant connector Weight, represented in ppm, 1-1000000
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
// validate input
require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
// special case for selling the entire supply
if (_sellAmount == _supply)
return _connectorBalance;
// special case if the weight = 100%
if (_connectorWeight == MAX_WEIGHT)
return _connectorBalance.mul(_sellAmount) / _supply;
uint256 result;
uint8 precision;
uint256 baseD = _supply - _sellAmount;
(result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
uint256 temp1 = _connectorBalance.mul(result);
uint256 temp2 = _connectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
@dev given two connector balances/weights and a sell amount (in the first connector token),
calculates the return for a conversion from the first connector token to the second connector token (in the second connector token)
Formula:
Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight))
@param _fromConnectorBalance input connector balance
@param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000
@param _toConnectorBalance output connector balance
@param _toConnectorWeight output connector weight, represented in ppm, 1-1000000
@param _amount input connector amount
@return second connector amount
*/
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) {
// validate input
require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT);
// special case for equal weights
if (_fromConnectorWeight == _toConnectorWeight)
return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount);
uint256 result;
uint8 precision;
uint256 baseN = _fromConnectorBalance.add(_amount);
(result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight);
uint256 temp1 = _toConnectorBalance.mul(result);
uint256 temp2 = _toConnectorBalance << precision;
return (temp1 - temp2) / result;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) {
require(_baseN < MAX_NUM);
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
}
else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
}
else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
if (_n < 256) {
// At most 8 iterations
while (_n > 1) {
_n >>= 1;
res += 1;
}
}
else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
require(false);
return 0;
}
/**
This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
Return log(x / FIXED_1) * FIXED_1
Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalLog.py'
Detailed description:
- Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2
- The natural logarithm of each (pre-calculated) exponent is the degree of the exponent
- The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1
- The natural logarithm of the input is calculated by summing up the intermediate results above
- For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859)
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
return res;
}
/**
Return e ^ (x / FIXED_1) * FIXED_1
Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalExp.py'
Detailed description:
- Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
- The exponentiation of each binary exponent is given (pre-calculated)
- The exponentiation of r is calculated via Taylor series for e^x, where x = r
- The exponentiation of the input is calculated by multiplying the intermediate results above
- For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3)
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
return res;
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol
pragma solidity 0.4.24;
contract IAragonFundraisingController {
function openTrading() external;
function updateTappedAmount(address _token) external;
function collateralsToBeClaimed(address _collateral) public view returns (uint256);
function balanceOf(address _who, address _token) public view returns (uint256);
}
// File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol
pragma solidity 0.4.24;
contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
uint32 public constant PPM = 1000000;
string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE";
string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO";
string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING";
string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL";
string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE";
string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT";
string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN";
string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN";
string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED";
string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED";
string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM";
string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER";
string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED";
string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED";
string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT";
string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE";
string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED";
struct Collateral {
bool whitelisted;
uint256 virtualSupply;
uint256 virtualBalance;
uint32 reserveRatio;
uint256 slippage;
}
struct MetaBatch {
bool initialized;
uint256 realSupply;
uint256 buyFeePct;
uint256 sellFeePct;
IBancorFormula formula;
mapping(address => Batch) batches;
}
struct Batch {
bool initialized;
bool cancelled;
uint256 supply;
uint256 balance;
uint32 reserveRatio;
uint256 slippage;
uint256 totalBuySpend;
uint256 totalBuyReturn;
uint256 totalSellSpend;
uint256 totalSellReturn;
mapping(address => uint256) buyers;
mapping(address => uint256) sellers;
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
Vault public reserve;
address public beneficiary;
IBancorFormula public formula;
uint256 public batchBlocks;
uint256 public buyFeePct;
uint256 public sellFeePct;
bool public isOpen;
uint256 public tokensToBeMinted;
mapping(address => uint256) public collateralsToBeClaimed;
mapping(address => Collateral) public collaterals;
mapping(uint256 => MetaBatch) public metaBatches;
event UpdateBeneficiary (address indexed beneficiary);
event UpdateFormula (address indexed formula);
event UpdateFees (uint256 buyFeePct, uint256 sellFeePct);
event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula);
event NewBatch (
uint256 indexed id,
address indexed collateral,
uint256 supply,
uint256 balance,
uint32 reserveRatio,
uint256 slippage)
;
event CancelBatch (uint256 indexed id, address indexed collateral);
event AddCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event RemoveCollateralToken (address indexed collateral);
event UpdateCollateralToken (
address indexed collateral,
uint256 virtualSupply,
uint256 virtualBalance,
uint32 reserveRatio,
uint256 slippage
);
event Open ();
event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount);
event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value);
event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value);
event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount);
event UpdatePricing (
uint256 indexed batchId,
address indexed collateral,
uint256 totalBuySpend,
uint256 totalBuyReturn,
uint256 totalSellSpend,
uint256 totalSellReturn
);
/***** external function *****/
/**
* @notice Initialize market maker
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded token] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom fees are to be sent]
* @param _formula The address of the BancorFormula [computation] contract
* @param _batchBlocks The number of blocks batches are to last
* @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
IBancorFormula _formula,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _buyFeePct,
uint256 _sellFeePct
)
external
onlyInit
{
initialized();
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS);
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING);
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(tokenManager.token());
formula = _formula;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
}
/* generic settings related function */
/**
* @notice Open market making [enabling users to open buy and sell orders]
*/
function open() external auth(OPEN_ROLE) {
require(!isOpen, ERROR_ALREADY_OPEN);
_open();
}
/**
* @notice Update formula to `_formula`
* @param _formula The address of the new BancorFormula [computation] contract
*/
function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) {
require(isContract(_formula), ERROR_CONTRACT_IS_EOA);
_updateFormula(_formula);
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE);
_updateFees(_buyFeePct, _sellFeePct);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
_removeCollateralToken(_collateral);
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* market making related functions */
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _buyer The address of the buyer
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE);
_openBuyOrder(_buyer, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _seller The address of the seller
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
require(isOpen, ERROR_NOT_OPEN);
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED);
require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT);
_openSellOrder(_seller, _collateral, _amount);
}
/**
* @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED);
require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER);
require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimSellOrder(_seller, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId`
* @param _buyer The address of the user whose cancelled buy orders are to be claimed
* @param _batchId The id of the batch in which cancelled buy orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed
*/
function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM);
_claimCancelledBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId`
* @param _seller The address of the user whose cancelled sell orders are to be claimed
* @param _batchId The id of the batch in which cancelled sell orders are to be claimed
* @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed
*/
function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized {
require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED);
require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM);
_claimCancelledSellOrder(_seller, _batchId, _collateral);
}
/***** public view functions *****/
function getCurrentBatchId() public view isInitialized returns (uint256) {
return _currentBatchId();
}
function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) {
Collateral storage collateral = collaterals[_collateral];
return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage);
}
function getBatch(uint256 _batchId, address _collateral)
public view isInitialized
returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256)
{
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return (
batch.initialized,
batch.cancelled,
batch.supply,
batch.balance,
batch.reserveRatio,
batch.slippage,
batch.totalBuySpend,
batch.totalBuyReturn,
batch.totalSellSpend,
batch.totalSellReturn
);
}
function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) {
return _staticPricePPM(_supply, _balance, _reserveRatio);
}
/***** internal functions *****/
/* computation functions */
function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) {
return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio)));
}
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _feeIsValid(uint256 _fee) internal pure returns (bool) {
return _fee < PCT_BASE;
}
function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) {
return _reserveRatio <= PPM;
}
function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) {
return _tokenManager.maxAccountTokens() == uint256(-1);
}
function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) {
if (_value == 0) {
return false;
}
if (_collateral == ETH) {
return _msgValue == _value;
}
return (
_msgValue == 0 &&
controller.balanceOf(_buyer, _collateral) >= _value &&
ERC20(_collateral).allowance(_buyer, address(this)) >= _value
);
}
function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) {
return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount;
}
function _collateralIsWhitelisted(address _collateral) internal view returns (bool) {
return collaterals[_collateral].whitelisted;
}
function _batchIsOver(uint256 _batchId) internal view returns (bool) {
return _batchId < _currentBatchId();
}
function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) {
return metaBatches[_batchId].batches[_collateral].cancelled;
}
function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.buyers[_user] > 0;
}
function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
return batch.sellers[_user] > 0;
}
function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) {
return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral];
}
function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) {
uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio);
uint256 maximumSlippage = _batch.slippage;
// if static price is zero let's consider that every slippage is valid
if (staticPricePPM == 0) {
return true;
}
return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage);
}
function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
/**
* NOTE
* slippage is valid if:
* totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE))
* totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE)
* totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM
*/
if (
_batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >=
_batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM))
) {
return true;
}
return false;
}
function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) {
/**
* NOTE
* the case where starting price is zero is handled
* in the meta function _slippageIsValid()
*/
// if allowed sell slippage >= 100%
// then any sell slippage is valid
if (_maximumSlippage >= PCT_BASE) {
return true;
}
/**
* NOTE
* slippage is valid if
* totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend
* totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE
* totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend
*/
if (
_batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >=
_startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend)
) {
return true;
}
return false;
}
/* initialization functions */
function _currentBatch(address _collateral) internal returns (uint256, Batch storage) {
uint256 batchId = _currentBatchId();
MetaBatch storage metaBatch = metaBatches[batchId];
Batch storage batch = metaBatch.batches[_collateral];
if (!metaBatch.initialized) {
/**
* NOTE
* all collateral batches should be initialized with the same supply to
* avoid price manipulation between different collaterals in the same meta-batch
* we don't need to do the same with collateral balances as orders against one collateral
* can't affect the pool's balance against another collateral and tap is a step-function
* of the meta-batch duration
*/
/**
* NOTE
* realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization)
* 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted
* should not be taken into account in the price computation [they are already a part of the batched pricing computation]
* 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders]
* is for buy orders from previous meta-batches to be claimed [and tokens to be minted]:
* as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization)
*/
metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted);
metaBatch.buyFeePct = buyFeePct;
metaBatch.sellFeePct = sellFeePct;
metaBatch.formula = formula;
metaBatch.initialized = true;
emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula);
}
if (!batch.initialized) {
/**
* NOTE
* supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization)
* virtualSupply can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
/**
* NOTE
* balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization)
* 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed
* should not be taken into account in the price computation [they are already a part of the batched price computation]
* 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders]
* is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration:
* as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization)
* 3. virtualBalance can technically be updated during a batch: the on-going batch will still use
* its value at the time of initialization [it's up to the updater to act wisely]
*/
controller.updateTappedAmount(_collateral);
batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply);
batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]);
batch.reserveRatio = collaterals[_collateral].reserveRatio;
batch.slippage = collaterals[_collateral].slippage;
batch.initialized = true;
emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage);
}
return (batchId, batch);
}
/* state modifiying functions */
function _open() internal {
isOpen = true;
emit Open();
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateFormula(IBancorFormula _formula) internal {
formula = _formula;
emit UpdateFormula(address(_formula));
}
function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal {
buyFeePct = _buyFeePct;
sellFeePct = _sellFeePct;
emit UpdateFees(_buyFeePct, _sellFeePct);
}
function _cancelCurrentBatch(address _collateral) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
if (!batch.cancelled) {
batch.cancelled = true;
// bought bonds are cancelled but sold bonds are due back
// bought collaterals are cancelled but sold collaterals are due back
tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn);
emit CancelBatch(batchId, _collateral);
}
}
function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage)
internal
{
collaterals[_collateral].whitelisted = true;
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _removeCollateralToken(address _collateral) internal {
_cancelCurrentBatch(_collateral);
Collateral storage collateral = collaterals[_collateral];
delete collateral.whitelisted;
delete collateral.virtualSupply;
delete collateral.virtualBalance;
delete collateral.reserveRatio;
delete collateral.slippage;
emit RemoveCollateralToken(_collateral);
}
function _updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
internal
{
collaterals[_collateral].virtualSupply = _virtualSupply;
collaterals[_collateral].virtualBalance = _virtualBalance;
collaterals[_collateral].reserveRatio = _reserveRatio;
collaterals[_collateral].slippage = _slippage;
emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// deduct fee
uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE);
uint256 value = _value.sub(fee);
// collect fee and collateral
if (fee > 0) {
_transfer(_buyer, beneficiary, _collateral, fee);
}
_transfer(_buyer, address(reserve), _collateral, value);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalBuySpend = batch.totalBuySpend.add(value);
batch.buyers[_buyer] = batch.buyers[_buyer].add(value);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value);
}
function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal {
(uint256 batchId, Batch storage batch) = _currentBatch(_collateral);
// burn bonds
tokenManager.burn(_seller, _amount);
// save batch
uint256 deprecatedBuyReturn = batch.totalBuyReturn;
uint256 deprecatedSellReturn = batch.totalSellReturn;
// update batch
batch.totalSellSpend = batch.totalSellSpend.add(_amount);
batch.sellers[_seller] = batch.sellers[_seller].add(_amount);
// update pricing
_updatePricing(batch, batchId, _collateral);
// update the amount of tokens to be minted and collaterals to be claimed
tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn);
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn);
// sanity checks
require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT);
require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE);
emit OpenSellOrder(_seller, batchId, _collateral, _amount);
}
function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend);
batch.buyers[_buyer] = 0;
if (buyReturn > 0) {
tokensToBeMinted = tokensToBeMinted.sub(buyReturn);
tokenManager.mint(_buyer, buyReturn);
}
emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn);
}
function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend);
uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE);
uint256 value = saleReturn.sub(fee);
batch.sellers[_seller] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn);
reserve.transfer(_collateral, _seller, value);
}
if (fee > 0) {
reserve.transfer(_collateral, beneficiary, fee);
}
emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value);
}
function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 value = batch.buyers[_buyer];
batch.buyers[_buyer] = 0;
if (value > 0) {
collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value);
reserve.transfer(_collateral, _buyer, value);
}
emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value);
}
function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal {
Batch storage batch = metaBatches[_batchId].batches[_collateral];
uint256 amount = batch.sellers[_seller];
batch.sellers[_seller] = 0;
if (amount > 0) {
tokensToBeMinted = tokensToBeMinted.sub(amount);
tokenManager.mint(_seller, amount);
}
emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount);
}
function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal {
// the situation where there are no buy nor sell orders can't happen [keep commented]
// if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0)
// return;
// static price is the current exact price in collateral
// per token according to the initial state of the batch
// [expressed in PPM for precision sake]
uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio);
// [NOTE]
// if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend
// so totalSellReturn will be zero and totalBuyReturn will be
// computed normally along the formula
// 1. we want to find out if buy orders are worth more sell orders [or vice-versa]
// 2. we thus check the return of sell orders at the current exact price
// 3. if the return of sell orders is larger than the pending buys,
// there are more sells than buys [and vice-versa]
uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM));
if (resultOfSell > batch.totalBuySpend) {
// >> sell orders are worth more than buy orders
// 1. first we execute all pending buy orders at the current exact
// price because there is at least one sell order for each buy order
// 2. then the final sell return is the addition of this first
// matched return with the remaining bonding curve return
// the number of tokens bought as a result of all buy orders matched at the
// current exact price [which is less than the total amount of tokens to be sold]
batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM);
// the number of tokens left over to be sold along the curve which is the difference
// between the original total sell order and the result of all the buy orders
uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn);
// the amount of collateral generated by selling tokens left over to be sold
// along the bonding curve in the batch initial state [as if the buy orders
// never existed and the sell order was just smaller than originally thought]
uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell);
// the total result of all sells is the original amount of buys which were matched
// plus the remaining sells which were executed along the bonding curve
batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn);
} else {
// >> buy orders are worth more than sell orders
// 1. first we execute all pending sell orders at the current exact
// price because there is at least one buy order for each sell order
// 2. then the final buy return is the addition of this first
// matched return with the remaining bonding curve return
// the number of collaterals bought as a result of all sell orders matched at the
// current exact price [which is less than the total amount of collateral to be spent]
batch.totalSellReturn = resultOfSell;
// the number of collaterals left over to be spent along the curve which is the difference
// between the original total buy order and the result of all the sell orders
uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell);
// the amount of tokens generated by selling collaterals left over to be spent
// along the bonding curve in the batch initial state [as if the sell orders
// never existed and the buy order was just smaller than originally thought]
uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy);
// the total result of all buys is the original amount of buys which were matched
// plus the remaining buys which were executed along the bonding curve
batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn);
}
emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn);
}
function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal {
if (_collateralToken == ETH) {
_to.transfer(_amount);
} else {
require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED);
}
}
}
// File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol
pragma solidity 0.4.24;
contract IPresale {
function open() external;
function close() external;
function contribute(address _contributor, uint256 _value) external payable;
function refund(address _contributor, uint256 _vestedPurchaseId) external;
function contributionToTokens(uint256 _value) public view returns (uint256);
function contributionToken() public view returns (address);
}
// File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol
pragma solidity 0.4.24;
contract ITap {
function updateBeneficiary(address _beneficiary) external;
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external;
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external;
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external;
function resetTappedToken(address _token) external;
function updateTappedAmount(address _token) external;
function withdraw(address _token) external;
function getMaximumWithdrawal(address _token) public view returns (uint256);
function rates(address _token) public view returns (uint256);
}
// File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol
pragma solidity 0.4.24;
contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE");
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE");
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE");
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE");
bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE");
bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE");
bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822;
bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d;
bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2;
bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207;
bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416;
bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2;
bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7;
bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant TO_RESET_CAP = 10;
string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS";
IPresale public presale;
BatchedBancorMarketMaker public marketMaker;
Agent public reserve;
ITap public tap;
address[] public toReset;
/***** external functions *****/
/**
* @notice Initialize Aragon Fundraising controller
* @param _presale The address of the presale contract
* @param _marketMaker The address of the market maker contract
* @param _reserve The address of the reserve [pool] contract
* @param _tap The address of the tap contract
* @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open]
*/
function initialize(
IPresale _presale,
BatchedBancorMarketMaker _marketMaker,
Agent _reserve,
ITap _tap,
address[] _toReset
)
external
onlyInit
{
require(isContract(_presale), ERROR_CONTRACT_IS_EOA);
require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(isContract(_tap), ERROR_CONTRACT_IS_EOA);
require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS);
initialized();
presale = _presale;
marketMaker = _marketMaker;
reserve = _reserve;
tap = _tap;
for (uint256 i = 0; i < _toReset.length; i++) {
require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS);
toReset.push(_toReset[i]);
}
}
/* generic settings related function */
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
marketMaker.updateBeneficiary(_beneficiary);
tap.updateBeneficiary(_beneficiary);
}
/**
* @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`%
* @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE]
* @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE]
*/
function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) {
marketMaker.updateFees(_buyFeePct, _sellFeePct);
}
/* presale related functions */
/**
* @notice Open presale
*/
function openPresale() external auth(OPEN_PRESALE_ROLE) {
presale.open();
}
/**
* @notice Close presale and open trading
*/
function closePresale() external isInitialized {
presale.close();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution token to be spent
*/
function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) {
presale.contribute.value(msg.value)(msg.sender, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized {
presale.refund(_contributor, _vestedPurchaseId);
}
/* market making related functions */
/**
* @notice Open trading [enabling users to open buy and sell orders]
*/
function openTrading() external auth(OPEN_TRADING_ROLE) {
for (uint256 i = 0; i < toReset.length; i++) {
if (tap.rates(toReset[i]) != uint256(0)) {
tap.resetTappedToken(toReset[i]);
}
}
marketMaker.open();
}
/**
* @notice Open a buy order worth `@tokenAmount(_collateral, _value)`
* @param _collateral The address of the collateral token to be spent
* @param _value The amount of collateral token to be spent
*/
function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) {
marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value);
}
/**
* @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string`
* @param _collateral The address of the collateral token to be returned
* @param _amount The amount of bonded token to be spent
*/
function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) {
marketMaker.openSellOrder(msg.sender, _collateral, _amount);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId`
* @param _buyer The address of the user whose buy orders are to be claimed
* @param _batchId The id of the batch in which buy orders are to be claimed
* @param _collateral The address of the collateral token against which buy orders are to be claimed
*/
function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimBuyOrder(_buyer, _batchId, _collateral);
}
/**
* @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId`
* @param _seller The address of the user whose sell orders are to be claimed
* @param _batchId The id of the batch in which sell orders are to be claimed
* @param _collateral The address of the collateral token against which sell orders are to be claimed
*/
function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized {
marketMaker.claimSellOrder(_seller, _batchId, _collateral);
}
/* collateral tokens related functions */
/**
* @notice Add `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage,
uint256 _rate,
uint256 _floor
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
if (_collateral != ETH) {
reserve.addProtectedToken(_collateral);
}
if (_rate > 0) {
tap.addTappedToken(_collateral, _rate, _floor);
}
}
/**
* @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past]
* @param _collateral The address of the collateral token to be whitelisted
* @param _virtualSupply The virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function reAddCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(ADD_COLLATERAL_TOKEN_ROLE)
{
marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/**
* @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token
* @param _collateral The address of the collateral token to be un-whitelisted
*/
function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) {
marketMaker.removeCollateralToken(_collateral);
// the token should still be tapped to avoid being locked
// the token should still be protected to avoid being spent
}
/**
* @notice Update `_collateral.symbol(): string` collateralization settings
* @param _collateral The address of the collateral token whose collateralization settings are to be updated
* @param _virtualSupply The new virtual supply to be used for that collateral token [in wei]
* @param _virtualBalance The new virtual balance to be used for that collateral token [in wei]
* @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM]
* @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE]
*/
function updateCollateralToken(
address _collateral,
uint256 _virtualSupply,
uint256 _virtualBalance,
uint32 _reserveRatio,
uint256 _slippage
)
external
auth(UPDATE_COLLATERAL_TOKEN_ROLE)
{
marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage);
}
/* tap related functions */
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) {
tap.addTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) {
tap.updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
tap.updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary
* @param _token The address of the token to be transfered from the reserve to the beneficiary
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
tap.withdraw(_token);
}
/***** public view functions *****/
function token() public view isInitialized returns (address) {
return marketMaker.token();
}
function contributionToken() public view isInitialized returns (address) {
return presale.contributionToken();
}
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return tap.getMaximumWithdrawal(_token);
}
function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) {
return marketMaker.collateralsToBeClaimed(_collateral);
}
function balanceOf(address _who, address _token) public view isInitialized returns (uint256) {
uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who);
if (_who == address(reserve)) {
return balance.sub(tap.getMaximumWithdrawal(_token));
} else {
return balance;
}
}
/***** internal functions *****/
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
}
// File: @ablack/fundraising-presale/contracts/Presale.sol
pragma solidity ^0.4.24;
contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
/**
Hardcoded constants to save gas
bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE");
bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE");
*/
bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4;
bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07;
uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4
string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN";
string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL";
string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE";
string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD";
string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT";
string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE";
string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE";
string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE";
string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE";
string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND";
string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED";
enum State {
Pending, // presale is idle and pending to be started
Funding, // presale has started and contributors can purchase tokens
Refunding, // presale has not reached goal within period and contributors can claim refunds
GoalReached, // presale has reached goal within period and trading is ready to be open
Closed // presale has reached goal within period, has been closed and trading has been open
}
IAragonFundraisingController public controller;
TokenManager public tokenManager;
ERC20 public token;
address public reserve;
address public beneficiary;
address public contributionToken;
uint256 public goal;
uint64 public period;
uint256 public exchangeRate;
uint64 public vestingCliffPeriod;
uint64 public vestingCompletePeriod;
uint256 public supplyOfferedPct;
uint256 public fundingForBeneficiaryPct;
uint64 public openDate;
bool public isClosed;
uint64 public vestingCliffDate;
uint64 public vestingCompleteDate;
uint256 public totalRaised;
mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent)
event SetOpenDate (uint64 date);
event Close ();
event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId);
/***** external function *****/
/**
* @notice Initialize presale
* @param _controller The address of the controller contract
* @param _tokenManager The address of the [bonded] token manager contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent]
* @param _contributionToken The address of the token to be used to contribute
* @param _goal The goal to be reached by the end of that presale [in contribution token wei]
* @param _period The period within which to accept contribution for that presale
* @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM]
* @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed
* @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested
* @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM]
* @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM]
* @param _openDate The date upon which that presale is to be open [ignored if 0]
*/
function initialize(
IAragonFundraisingController _controller,
TokenManager _tokenManager,
address _reserve,
address _beneficiary,
address _contributionToken,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY);
require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN);
require(_goal > 0, ERROR_INVALID_GOAL);
require(_period > 0, ERROR_INVALID_TIME_PERIOD);
require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE);
require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD);
require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD);
require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT);
require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT);
initialized();
controller = _controller;
tokenManager = _tokenManager;
token = ERC20(_tokenManager.token());
reserve = _reserve;
beneficiary = _beneficiary;
contributionToken = _contributionToken;
goal = _goal;
period = _period;
exchangeRate = _exchangeRate;
vestingCliffPeriod = _vestingCliffPeriod;
vestingCompletePeriod = _vestingCompletePeriod;
supplyOfferedPct = _supplyOfferedPct;
fundingForBeneficiaryPct = _fundingForBeneficiaryPct;
if (_openDate != 0) {
_setOpenDate(_openDate);
}
}
/**
* @notice Open presale [enabling users to contribute]
*/
function open() external auth(OPEN_ROLE) {
require(state() == State.Pending, ERROR_INVALID_STATE);
require(openDate == 0, ERROR_INVALID_STATE);
_open();
}
/**
* @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)`
* @param _contributor The address of the contributor
* @param _value The amount of contribution token to be spent
*/
function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) {
require(state() == State.Funding, ERROR_INVALID_STATE);
require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE);
if (contributionToken == ETH) {
require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE);
} else {
require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE);
}
_contribute(_contributor, _value);
}
/**
* @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId`
* @param _contributor The address of the contributor whose presale contribution is to be refunded
* @param _vestedPurchaseId The id of the contribution to be refunded
*/
function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized {
require(state() == State.Refunding, ERROR_INVALID_STATE);
_refund(_contributor, _vestedPurchaseId);
}
/**
* @notice Close presale and open trading
*/
function close() external nonReentrant isInitialized {
require(state() == State.GoalReached, ERROR_INVALID_STATE);
_close();
}
/***** public view functions *****/
/**
* @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)`
* @param _value The amount of contribution tokens to be used in that computation
*/
function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) {
return _value.mul(exchangeRate).div(PPM);
}
function contributionToken() public view isInitialized returns (address) {
return contributionToken;
}
/**
* @notice Returns the current state of that presale
*/
function state() public view isInitialized returns (State) {
if (openDate == 0 || openDate > getTimestamp64()) {
return State.Pending;
}
if (totalRaised >= goal) {
if (isClosed) {
return State.Closed;
} else {
return State.GoalReached;
}
}
if (_timeSinceOpen() < period) {
return State.Funding;
} else {
return State.Refunding;
}
}
/***** internal functions *****/
function _timeSinceOpen() internal view returns (uint64) {
if (openDate == 0) {
return 0;
} else {
return getTimestamp64().sub(openDate);
}
}
function _setOpenDate(uint64 _date) internal {
require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD);
openDate = _date;
_setVestingDatesWhenOpenDateIsKnown();
emit SetOpenDate(_date);
}
function _setVestingDatesWhenOpenDateIsKnown() internal {
vestingCliffDate = openDate.add(vestingCliffPeriod);
vestingCompleteDate = openDate.add(vestingCompletePeriod);
}
function _open() internal {
_setOpenDate(getTimestamp64());
}
function _contribute(address _contributor, uint256 _value) internal {
uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value;
if (contributionToken == ETH && _value > value) {
msg.sender.transfer(_value.sub(value));
}
// (contributor) ~~~> contribution tokens ~~~> (presale)
if (contributionToken != ETH) {
require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE);
require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE);
_transfer(contributionToken, _contributor, address(this), value);
}
// (mint ✨) ~~~> project tokens ~~~> (contributor)
uint256 tokensToSell = contributionToTokens(value);
tokenManager.issue(tokensToSell);
uint256 vestedPurchaseId = tokenManager.assignVested(
_contributor,
tokensToSell,
openDate,
vestingCliffDate,
vestingCompleteDate,
true /* revokable */
);
totalRaised = totalRaised.add(value);
// register contribution tokens spent in this purchase for a possible upcoming refund
contributions[_contributor][vestedPurchaseId] = value;
emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId);
}
function _refund(address _contributor, uint256 _vestedPurchaseId) internal {
// recall how much contribution tokens are to be refund for this purchase
uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId];
require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND);
contributions[_contributor][_vestedPurchaseId] = 0;
// (presale) ~~~> contribution tokens ~~~> (contributor)
_transfer(contributionToken, address(this), _contributor, tokensToRefund);
/**
* NOTE
* the following lines assume that _contributor has not transfered any of its vested tokens
* for now TokenManager does not handle switching the transferrable status of its underlying token
* there is thus no way to enforce non-transferrability during the presale phase only
* this will be updated in a later version
*/
// (contributor) ~~~> project tokens ~~~> (token manager)
(uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId);
tokenManager.revokeVesting(_contributor, _vestedPurchaseId);
// (token manager) ~~~> project tokens ~~~> (burn 💥)
tokenManager.burn(address(tokenManager), tokensSold);
emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId);
}
function _close() internal {
isClosed = true;
// (presale) ~~~> contribution tokens ~~~> (beneficiary)
uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM);
if (fundsForBeneficiary > 0) {
_transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary);
}
// (presale) ~~~> contribution tokens ~~~> (reserve)
uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this));
_transfer(contributionToken, address(this), reserve, tokensForReserve);
// (mint ✨) ~~~> project tokens ~~~> (beneficiary)
uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct);
tokenManager.issue(tokensForBeneficiary);
tokenManager.assignVested(
beneficiary,
tokensForBeneficiary,
openDate,
vestingCliffDate,
vestingCompleteDate,
false /* revokable */
);
// open trading
controller.openTrading();
emit Close();
}
function _transfer(address _token, address _from, address _to, uint256 _amount) internal {
if (_token == ETH) {
require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED);
require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED);
_to.transfer(_amount);
} else {
if (_from == address(this)) {
require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
} else {
require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED);
}
}
}
}
// File: @ablack/fundraising-tap/contracts/Tap.sol
pragma solidity 0.4.24;
contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/**
Hardcoded constants to save gas
bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE");
bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE");
bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE");
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE");
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE");
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE");
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE");
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE");
bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
*/
bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30;
bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7;
bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593;
bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207;
bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1;
bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc;
bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd;
bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288;
bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e;
bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec;
uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18
string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA";
string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY";
string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS";
string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT";
string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN";
string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE";
string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE";
string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED";
string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED";
string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO";
IAragonFundraisingController public controller;
Vault public reserve;
address public beneficiary;
uint256 public batchBlocks;
uint256 public maximumTapRateIncreasePct;
uint256 public maximumTapFloorDecreasePct;
mapping (address => uint256) public tappedAmounts;
mapping (address => uint256) public rates;
mapping (address => uint256) public floors;
mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers]
mapping (address => uint256) public lastTapUpdates; // timestamps
event UpdateBeneficiary (address indexed beneficiary);
event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct);
event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct);
event AddTappedToken (address indexed token, uint256 rate, uint256 floor);
event RemoveTappedToken (address indexed token);
event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor);
event ResetTappedToken (address indexed token);
event UpdateTappedAmount (address indexed token, uint256 tappedAmount);
event Withdraw (address indexed token, uint256 amount);
/***** external functions *****/
/**
* @notice Initialize tap
* @param _controller The address of the controller contract
* @param _reserve The address of the reserve [pool] contract
* @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn]
* @param _batchBlocks The number of blocks batches are to last
* @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE]
* @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE]
*/
function initialize(
IAragonFundraisingController _controller,
Vault _reserve,
address _beneficiary,
uint256 _batchBlocks,
uint256 _maximumTapRateIncreasePct,
uint256 _maximumTapFloorDecreasePct
)
external
onlyInit
{
require(isContract(_controller), ERROR_CONTRACT_IS_EOA);
require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS);
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
initialized();
controller = _controller;
reserve = _reserve;
beneficiary = _beneficiary;
batchBlocks = _batchBlocks;
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
}
/**
* @notice Update beneficiary to `_beneficiary`
* @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn]
*/
function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) {
require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY);
_updateBeneficiary(_beneficiary);
}
/**
* @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`%
* @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) {
_updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
/**
* @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`%
* @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE]
*/
function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) {
require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT);
_updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
/**
* @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token to be tapped
* @param _rate The rate at which that token is to be tapped [in wei / block]
* @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) {
require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN);
require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
_addTappedToken(_token, _rate, _floor);
}
/**
* @notice Remove tap for `_token.symbol(): string`
* @param _token The address of the token to be un-tapped
*/
function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_removeTappedToken(_token);
}
/**
* @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)`
* @param _token The address of the token whose tap is to be updated
* @param _rate The new rate at which that token is to be tapped [in wei / block]
* @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei]
*/
function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE);
require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE);
_updateTappedToken(_token, _rate, _floor);
}
/**
* @notice Reset tap timestamps for `_token.symbol(): string`
* @param _token The address of the token whose tap timestamps are to be reset
*/
function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_resetTappedToken(_token);
}
/**
* @notice Update tapped amount for `_token.symbol(): string`
* @param _token The address of the token whose tapped amount is to be updated
*/
function updateTappedAmount(address _token) external {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
_updateTappedAmount(_token);
}
/**
* @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()`
* @param _token The address of the token to be transfered
*/
function withdraw(address _token) external auth(WITHDRAW_ROLE) {
require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED);
uint256 amount = _updateTappedAmount(_token);
require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO);
_withdraw(_token, amount);
}
/***** public view functions *****/
function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) {
return _tappedAmount(_token);
}
function rates(address _token) public view isInitialized returns (uint256) {
return rates[_token];
}
/***** internal functions *****/
/* computation functions */
function _currentBatchId() internal view returns (uint256) {
return (block.number.div(batchBlocks)).mul(batchBlocks);
}
function _tappedAmount(address _token) internal view returns (uint256) {
uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]);
uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve);
uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]);
uint256 tappedAmount = tappedAmounts[_token].add(flow);
/**
* whatever happens enough collateral should be
* kept in the reserve pool to guarantee that
* its balance is kept above the floor once
* all pending sell orders are claimed
*/
/**
* the reserve's balance is already below the balance to be kept
* the tapped amount should be reset to zero
*/
if (balance <= toBeKept) {
return 0;
}
/**
* the reserve's balance minus the upcoming tap flow would be below the balance to be kept
* the flow should be reduced to balance - toBeKept
*/
if (balance <= toBeKept.add(tappedAmount)) {
return balance.sub(toBeKept);
}
/**
* the reserve's balance minus the upcoming flow is above the balance to be kept
* the flow can be added to the tapped amount
*/
return tappedAmount;
}
/* check functions */
function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) {
return _beneficiary != address(0);
}
function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) {
return _maximumTapFloorDecreasePct <= PCT_BASE;
}
function _tokenIsContractOrETH(address _token) internal view returns (bool) {
return isContract(_token) || _token == ETH;
}
function _tokenIsTapped(address _token) internal view returns (bool) {
return rates[_token] != uint256(0);
}
function _tapRateIsValid(uint256 _rate) internal pure returns (bool) {
return _rate != 0;
}
function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) {
return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor);
}
function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) {
uint256 rate = rates[_token];
if (_rate <= rate) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) {
return true;
}
return false;
}
function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) {
uint256 floor = floors[_token];
if (_floor >= floor) {
return true;
}
if (getTimestamp() < lastTapUpdates[_token] + 30 days) {
return false;
}
if (maximumTapFloorDecreasePct >= PCT_BASE) {
return true;
}
if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) {
return true;
}
return false;
}
/* state modifying functions */
function _updateTappedAmount(address _token) internal returns (uint256) {
uint256 tappedAmount = _tappedAmount(_token);
lastTappedAmountUpdates[_token] = _currentBatchId();
tappedAmounts[_token] = tappedAmount;
emit UpdateTappedAmount(_token, tappedAmount);
return tappedAmount;
}
function _updateBeneficiary(address _beneficiary) internal {
beneficiary = _beneficiary;
emit UpdateBeneficiary(_beneficiary);
}
function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal {
maximumTapRateIncreasePct = _maximumTapRateIncreasePct;
emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct);
}
function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal {
maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct;
emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct);
}
function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* 1. if _token is tapped in the middle of a batch it will
* reach the next batch faster than what it normally takes
* to go through a batch [e.g. one block later]
* 2. this will allow for a higher withdrawal than expected
* a few blocks after _token is tapped
* 3. this is not a problem because this extra amount is
* static [at most rates[_token] * batchBlocks] and does
* not increase in time
*/
rates[_token] = _rate;
floors[_token] = _floor;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit AddTappedToken(_token, _rate, _floor);
}
function _removeTappedToken(address _token) internal {
delete tappedAmounts[_token];
delete rates[_token];
delete floors[_token];
delete lastTappedAmountUpdates[_token];
delete lastTapUpdates[_token];
emit RemoveTappedToken(_token);
}
function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal {
/**
* NOTE
* withdraw before updating to keep the reserve
* actual balance [balance - virtual withdrawal]
* continuous in time [though a floor update can
* still break this continuity]
*/
uint256 amount = _updateTappedAmount(_token);
if (amount > 0) {
_withdraw(_token, amount);
}
rates[_token] = _rate;
floors[_token] = _floor;
lastTapUpdates[_token] = getTimestamp();
emit UpdateTappedToken(_token, _rate, _floor);
}
function _resetTappedToken(address _token) internal {
tappedAmounts[_token] = 0;
lastTappedAmountUpdates[_token] = _currentBatchId();
lastTapUpdates[_token] = getTimestamp();
emit ResetTappedToken(_token);
}
function _withdraw(address _token, uint256 _amount) internal {
tappedAmounts[_token] = tappedAmounts[_token].sub(_amount);
reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error
emit Withdraw(_token, _amount);
}
}
// File: contracts/AavegotchiTBCTemplate.sol
pragma solidity 0.4.24;
contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate {
string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS";
string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE";
bool private constant BOARD_TRANSFERABLE = false;
uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0);
uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1);
bool private constant SHARE_TRANSFERABLE = true;
uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18);
uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0);
uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days);
uint256 private constant BUY_FEE_PCT = 0;
uint256 private constant SELL_FEE_PCT = 0;
uint32 private constant DAI_RESERVE_RATIO = 333333; // 33%
uint32 private constant ANT_RESERVE_RATIO = 10000; // 1%
bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d;
bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5;
bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0;
bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac;
bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc;
struct Cache {
address dao;
address boardTokenManager;
address boardVoting;
address vault;
address finance;
address shareVoting;
address shareTokenManager;
address reserve;
address presale;
address marketMaker;
address tap;
address controller;
}
address[] public collaterals;
mapping (address => Cache) private cache;
constructor(
DAOFactory _daoFactory,
ENS _ens,
MiniMeTokenFactory _miniMeFactory,
IFIFSResolvingRegistrar _aragonID,
address _dai,
address _ant
)
BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID)
public
{
_ensureAragonIdIsValid(_aragonID);
_ensureMiniMeFactoryIsValid(_miniMeFactory);
require(isContract(_dai), ERROR_BAD_SETTINGS);
require(isContract(_ant), ERROR_BAD_SETTINGS);
require(_dai != _ant, ERROR_BAD_SETTINGS);
collaterals.push(_dai);
collaterals.push(_ant);
}
/***** external functions *****/
function prepareInstance(
string _boardTokenName,
string _boardTokenSymbol,
address[] _boardMembers,
uint64[3] _boardVotingSettings,
uint64 _financePeriod
)
external
{
require(_boardMembers.length > 0, ERROR_BAD_SETTINGS);
require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS);
// deploy DAO
(Kernel dao, ACL acl) = _createDAO();
// deploy board token
MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS);
// install board apps
TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod);
// mint board tokens
_mintTokens(acl, tm, _boardMembers, 1);
// cache DAO
_cacheDao(dao);
}
function installShareApps(
string _shareTokenName,
string _shareTokenSymbol,
uint64[3] _shareVotingSettings
)
external
{
require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS);
_ensureBoardAppsCache();
Kernel dao = _daoCache();
// deploy share token
MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS);
// install share apps
_installShareApps(dao, shareToken, _shareVotingSettings);
// setup board apps permissions [now that share apps have been installed]
_setupBoardPermissions(dao);
}
function installFundraisingApps(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
external
{
_ensureShareAppsCache();
Kernel dao = _daoCache();
// install fundraising apps
_installFundraisingApps(
dao,
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate,
_batchBlocks,
_maxTapRateIncreasePct,
_maxTapFloorDecreasePct
);
// setup share apps permissions [now that fundraising apps have been installed]
_setupSharePermissions(dao);
// setup fundraising apps permissions
_setupFundraisingPermissions(dao);
}
function finalizeInstance(
string _id,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
external
{
require(bytes(_id).length > 0, ERROR_BAD_SETTINGS);
require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS);
require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS);
require(_slippages.length == 2, ERROR_BAD_SETTINGS);
_ensureFundraisingAppsCache();
Kernel dao = _daoCache();
ACL acl = ACL(dao.acl());
(, Voting shareVoting) = _shareAppsCache();
// setup collaterals
_setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI);
// setup EVM script registry permissions
_createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting);
// clear DAO permissions
_transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting);
// register id
_registerID(_id, address(dao));
// clear cache
_clearCache();
}
/***** internal apps installation functions *****/
function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod)
internal
returns (TokenManager)
{
TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _token, _votingSettings);
Vault vault = _installVaultApp(_dao);
Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod);
_cacheBoardApps(tm, voting, vault, finance);
return tm;
}
function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings)
internal
{
TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT);
Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings);
_cacheShareApps(tm, voting);
}
function _installFundraisingApps(
Kernel _dao,
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate,
uint256 _batchBlocks,
uint256 _maxTapRateIncreasePct,
uint256 _maxTapFloorDecreasePct
)
internal
{
_proxifyFundraisingApps(_dao);
_initializePresale(
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
_initializeMarketMaker(_batchBlocks);
_initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
_initializeController();
}
function _proxifyFundraisingApps(Kernel _dao) internal {
Agent reserve = _installNonDefaultAgentApp(_dao);
Presale presale = Presale(_registerApp(_dao, PRESALE_ID));
BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID));
Tap tap = Tap(_registerApp(_dao, TAP_ID));
AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID));
_cacheFundraisingApps(reserve, presale, marketMaker, tap, controller);
}
/***** internal apps initialization functions *****/
function _initializePresale(
uint256 _goal,
uint64 _period,
uint256 _exchangeRate,
uint64 _vestingCliffPeriod,
uint64 _vestingCompletePeriod,
uint256 _supplyOfferedPct,
uint256 _fundingForBeneficiaryPct,
uint64 _openDate
)
internal
{
_presaleCache().initialize(
_controllerCache(),
_shareTMCache(),
_reserveCache(),
_vaultCache(),
collaterals[0],
_goal,
_period,
_exchangeRate,
_vestingCliffPeriod,
_vestingCompletePeriod,
_supplyOfferedPct,
_fundingForBeneficiaryPct,
_openDate
);
}
function _initializeMarketMaker(uint256 _batchBlocks) internal {
IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID));
(,, Vault beneficiary,) = _boardAppsCache();
(TokenManager shareTM,) = _shareAppsCache();
(Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache();
marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT);
}
function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal {
(,, Vault beneficiary,) = _boardAppsCache();
(Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct);
}
function _initializeController() internal {
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
address[] memory toReset = new address[](1);
toReset[0] = collaterals[0];
controller.initialize(presale, marketMaker, reserve, tap, toReset);
}
/***** internal setup functions *****/
function _setupCollaterals(
Kernel _dao,
uint256[2] _virtualSupplies,
uint256[2] _virtualBalances,
uint256[2] _slippages,
uint256 _rateDAI,
uint256 _floorDAI
)
internal
{
ACL acl = ACL(_dao.acl());
(, Voting shareVoting) = _shareAppsCache();
(,,,, AragonFundraisingController controller) = _fundraisingAppsCache();
// create and grant ADD_COLLATERAL_TOKEN_ROLE to this template
_createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE());
// add DAI both as a protected collateral and a tapped token
controller.addCollateralToken(
collaterals[0],
_virtualSupplies[0],
_virtualBalances[0],
DAI_RESERVE_RATIO,
_slippages[0],
_rateDAI,
_floorDAI
);
// add ANT as a protected collateral [but not as a tapped token]
controller.addCollateralToken(
collaterals[1],
_virtualSupplies[1],
_virtualBalances[1],
ANT_RESERVE_RATIO,
_slippages[1],
0,
0
);
// transfer ADD_COLLATERAL_TOKEN_ROLE
_transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
}
/***** internal permissions functions *****/
function _setupBoardPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
// token manager
_createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting);
// voting
_createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting);
// vault
_createVaultPermissions(acl, vault, finance, shareVoting);
// finance
_createFinancePermissions(acl, finance, boardVoting, shareVoting);
_createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting);
}
function _setupSharePermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(TokenManager boardTM,,,) = _boardAppsCache();
(TokenManager shareTM, Voting shareVoting) = _shareAppsCache();
(, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache();
// token manager
address[] memory grantees = new address[](2);
grantees[0] = address(marketMaker);
grantees[1] = address(presale);
acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting);
acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting);
_createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting);
// voting
_createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting);
}
function _setupFundraisingPermissions(Kernel _dao) internal {
ACL acl = ACL(_dao.acl());
(, Voting boardVoting,,) = _boardAppsCache();
(, Voting shareVoting) = _shareAppsCache();
(Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache();
// reserve
address[] memory grantees = new address[](2);
grantees[0] = address(tap);
grantees[1] = address(marketMaker);
acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting);
acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting);
_createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting);
// presale
acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting);
// market maker
acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting);
// tap
acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting);
acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting);
// controller
// ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added]
acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting);
// acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting);
acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting);
acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting);
acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting);
}
/***** internal cache functions *****/
function _cacheDao(Kernel _dao) internal {
Cache storage c = cache[msg.sender];
c.dao = address(_dao);
}
function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal {
Cache storage c = cache[msg.sender];
c.boardTokenManager = address(_boardTM);
c.boardVoting = address(_boardVoting);
c.vault = address(_vault);
c.finance = address(_finance);
}
function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal {
Cache storage c = cache[msg.sender];
c.shareTokenManager = address(_shareTM);
c.shareVoting = address(_shareVoting);
}
function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal {
Cache storage c = cache[msg.sender];
c.reserve = address(_reserve);
c.presale = address(_presale);
c.marketMaker = address(_marketMaker);
c.tap = address(_tap);
c.controller = address(_controller);
}
function _daoCache() internal view returns (Kernel dao) {
Cache storage c = cache[msg.sender];
dao = Kernel(c.dao);
}
function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) {
Cache storage c = cache[msg.sender];
boardTM = TokenManager(c.boardTokenManager);
boardVoting = Voting(c.boardVoting);
vault = Vault(c.vault);
finance = Finance(c.finance);
}
function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
shareVoting = Voting(c.shareVoting);
}
function _fundraisingAppsCache() internal view returns (
Agent reserve,
Presale presale,
BatchedBancorMarketMaker marketMaker,
Tap tap,
AragonFundraisingController controller
)
{
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
presale = Presale(c.presale);
marketMaker = BatchedBancorMarketMaker(c.marketMaker);
tap = Tap(c.tap);
controller = AragonFundraisingController(c.controller);
}
function _clearCache() internal {
Cache storage c = cache[msg.sender];
delete c.dao;
delete c.boardTokenManager;
delete c.boardVoting;
delete c.vault;
delete c.finance;
delete c.shareVoting;
delete c.shareTokenManager;
delete c.reserve;
delete c.presale;
delete c.marketMaker;
delete c.tap;
delete c.controller;
}
/**
* NOTE
* the following functions are only needed for the presale
* initialization function [which we can't compile otherwise
* because of a `stack too deep` error]
*/
function _vaultCache() internal view returns (Vault vault) {
Cache storage c = cache[msg.sender];
vault = Vault(c.vault);
}
function _shareTMCache() internal view returns (TokenManager shareTM) {
Cache storage c = cache[msg.sender];
shareTM = TokenManager(c.shareTokenManager);
}
function _reserveCache() internal view returns (Agent reserve) {
Cache storage c = cache[msg.sender];
reserve = Agent(c.reserve);
}
function _presaleCache() internal view returns (Presale presale) {
Cache storage c = cache[msg.sender];
presale = Presale(c.presale);
}
function _controllerCache() internal view returns (AragonFundraisingController controller) {
Cache storage c = cache[msg.sender];
controller = AragonFundraisingController(c.controller);
}
/***** internal check functions *****/
function _ensureBoardAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.boardTokenManager != address(0) &&
c.boardVoting != address(0) &&
c.vault != address(0) &&
c.finance != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureShareAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.shareTokenManager != address(0) &&
c.shareVoting != address(0),
ERROR_MISSING_CACHE
);
}
function _ensureFundraisingAppsCache() internal view {
Cache storage c = cache[msg.sender];
require(
c.reserve != address(0) &&
c.presale != address(0) &&
c.marketMaker != address(0) &&
c.tap != address(0) &&
c.controller != address(0),
ERROR_MISSING_CACHE
);
}
/***** internal utils functions *****/
function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) {
address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId));
emit InstalledApp(proxy, _appId);
return proxy;
}
}
|
Queries the balance of `_owner` at a specific `_blockNumber` _owner The address from which the balance will be retrieved _blockNumber The block number when the balance is queried return The balance at `_blockNumber` These next few lines are used when the balance of the token is requested before a check point was ever created for this token, it requires that the `parentToken.balanceOfAt` be queried at the genesis block for that token as this contains initial balance of this token Has no parent
|
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
return 0;
}
return getValueAt(balances[_owner], _blockNumber);
}
}
| 451,011
|
pragma solidity ^0.4.16;
// copyright contact@Etheremon.com
contract SafeMath {
/* function assert(bool assertion) internal { */
/* if (!assertion) { */
/* throw; */
/* } */
/* } // assert no longer needed once solidity is on 0.4.10 */
function safeAdd(uint256 x, uint256 y) pure internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) pure internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) pure internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract BasicAccessControl {
address public owner;
// address[] public moderators;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = false;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
}
contract EtheremonEnum {
enum ResultCode {
SUCCESS,
ERROR_CLASS_NOT_FOUND,
ERROR_LOW_BALANCE,
ERROR_SEND_FAIL,
ERROR_NOT_TRAINER,
ERROR_NOT_ENOUGH_MONEY,
ERROR_INVALID_AMOUNT
}
enum ArrayType {
CLASS_TYPE,
STAT_STEP,
STAT_START,
STAT_BASE,
OBJ_SKILL
}
enum PropertyType {
ANCESTOR,
XFACTOR
}
}
contract EtheremonDataBase is EtheremonEnum, BasicAccessControl, SafeMath {
uint64 public totalMonster;
uint32 public totalClass;
// write
function withdrawEther(address _sendTo, uint _amount) onlyOwner public returns(ResultCode);
function addElementToArrayType(ArrayType _type, uint64 _id, uint8 _value) onlyModerators public returns(uint);
function updateIndexOfArrayType(ArrayType _type, uint64 _id, uint _index, uint8 _value) onlyModerators public returns(uint);
function setMonsterClass(uint32 _classId, uint256 _price, uint256 _returnPrice, bool _catchable) onlyModerators public returns(uint32);
function addMonsterObj(uint32 _classId, address _trainer, string _name) onlyModerators public returns(uint64);
function setMonsterObj(uint64 _objId, string _name, uint32 _exp, uint32 _createIndex, uint32 _lastClaimIndex) onlyModerators public;
function increaseMonsterExp(uint64 _objId, uint32 amount) onlyModerators public;
function decreaseMonsterExp(uint64 _objId, uint32 amount) onlyModerators public;
function removeMonsterIdMapping(address _trainer, uint64 _monsterId) onlyModerators public;
function addMonsterIdMapping(address _trainer, uint64 _monsterId) onlyModerators public;
function clearMonsterReturnBalance(uint64 _monsterId) onlyModerators public returns(uint256 amount);
function collectAllReturnBalance(address _trainer) onlyModerators public returns(uint256 amount);
function transferMonster(address _from, address _to, uint64 _monsterId) onlyModerators public returns(ResultCode);
function addExtraBalance(address _trainer, uint256 _amount) onlyModerators public returns(uint256);
function deductExtraBalance(address _trainer, uint256 _amount) onlyModerators public returns(uint256);
function setExtraBalance(address _trainer, uint256 _amount) onlyModerators public;
// read
function getSizeArrayType(ArrayType _type, uint64 _id) constant public returns(uint);
function getElementInArrayType(ArrayType _type, uint64 _id, uint _index) constant public returns(uint8);
function getMonsterClass(uint32 _classId) constant public returns(uint32 classId, uint256 price, uint256 returnPrice, uint32 total, bool catchable);
function getMonsterObj(uint64 _objId) constant public returns(uint64 objId, uint32 classId, address trainer, uint32 exp, uint32 createIndex, uint32 lastClaimIndex, uint createTime);
function getMonsterName(uint64 _objId) constant public returns(string name);
function getExtraBalance(address _trainer) constant public returns(uint256);
function getMonsterDexSize(address _trainer) constant public returns(uint);
function getMonsterObjId(address _trainer, uint index) constant public returns(uint64);
function getExpectedBalance(address _trainer) constant public returns(uint256);
function getMonsterReturn(uint64 _objId) constant public returns(uint256 current, uint256 total);
}
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);
}
contract BattleInterface {
function createCastleWithToken(address _trainer, uint32 _noBrick, string _name, uint64 _a1, uint64 _a2, uint64 _a3, uint64 _s1, uint64 _s2, uint64 _s3) external;
}
contract TransformInterface {
function removeHatchingTimeWithToken(address _trainer) external;
function buyEggWithToken(address _trainer) external;
}
contract AdventureInterface {
function placeEMONTBid(address _bidder, uint8 _siteId, uint _bidAmount) external;
}
contract EtheremonPayment is EtheremonEnum, BasicAccessControl, SafeMath {
uint8 constant public STAT_COUNT = 6;
uint8 constant public STAT_MAX = 32;
uint8 constant public GEN0_NO = 24;
enum PayServiceType {
NONE,
FAST_HATCHING,
RANDOM_EGG,
ADVENTURE_PRESALE
}
struct MonsterClassAcc {
uint32 classId;
uint256 price;
uint256 returnPrice;
uint32 total;
bool catchable;
}
struct MonsterObjAcc {
uint64 monsterId;
uint32 classId;
address trainer;
string name;
uint32 exp;
uint32 createIndex;
uint32 lastClaimIndex;
uint createTime;
}
// linked smart contract
address public dataContract;
address public battleContract;
address public tokenContract;
address public transformContract;
address public adventureContract;
address private lastHunter = address(0x0);
// config
uint public brickPrice = 6 * 10 ** 8; // 6 tokens
uint public fastHatchingPrice = 35 * 10 ** 8; // 15 tokens
uint public buyEggPrice = 80 * 10 ** 8; // 80 tokens
uint public tokenPrice = 0.004 ether / 10 ** 8;
uint public maxDexSize = 200;
// event
event EventCatchMonster(address indexed trainer, uint64 objId);
// modifier
modifier requireDataContract {
require(dataContract != address(0));
_;
}
modifier requireBattleContract {
require(battleContract != address(0));
_;
}
modifier requireTokenContract {
require(tokenContract != address(0));
_;
}
modifier requireTransformContract {
require(transformContract != address(0));
_;
}
function EtheremonPayment(address _dataContract, address _battleContract, address _tokenContract, address _transformContract, address _adventureContract) public {
dataContract = _dataContract;
battleContract = _battleContract;
tokenContract = _tokenContract;
transformContract = _transformContract;
adventureContract = _adventureContract;
}
// helper
function getRandom(uint8 maxRan, uint8 index, address priAddress) constant public returns(uint8) {
uint256 genNum = uint256(block.blockhash(block.number-1)) + uint256(priAddress);
for (uint8 i = 0; i < index && i < 6; i ++) {
genNum /= 256;
}
return uint8(genNum % maxRan);
}
// admin
function withdrawToken(address _sendTo, uint _amount) onlyModerators requireTokenContract external {
ERC20Interface token = ERC20Interface(tokenContract);
if (_amount > token.balanceOf(address(this))) {
revert();
}
token.transfer(_sendTo, _amount);
}
function setContract(address _dataContract, address _battleContract, address _tokenContract, address _transformContract, address _adventureContract) onlyModerators external {
dataContract = _dataContract;
battleContract = _battleContract;
tokenContract = _tokenContract;
transformContract = _transformContract;
adventureContract = _adventureContract;
}
function setConfig(uint _brickPrice, uint _tokenPrice, uint _maxDexSize, uint _fastHatchingPrice, uint _buyEggPrice) onlyModerators external {
brickPrice = _brickPrice;
tokenPrice = _tokenPrice;
maxDexSize = _maxDexSize;
fastHatchingPrice = _fastHatchingPrice;
buyEggPrice = _buyEggPrice;
}
// battle
function giveBattleBonus(address _trainer, uint _amount) isActive requireBattleContract requireTokenContract public {
if (msg.sender != battleContract)
revert();
ERC20Interface token = ERC20Interface(tokenContract);
token.transfer(_trainer, _amount);
}
function createCastle(address _trainer, uint _tokens, string _name, uint64 _a1, uint64 _a2, uint64 _a3, uint64 _s1, uint64 _s2, uint64 _s3) isActive requireBattleContract requireTokenContract public returns(uint){
if (msg.sender != tokenContract)
revert();
BattleInterface battle = BattleInterface(battleContract);
battle.createCastleWithToken(_trainer, uint32(_tokens/brickPrice), _name, _a1, _a2, _a3, _s1, _s2, _s3);
return _tokens;
}
function catchMonster(address _trainer, uint _tokens, uint32 _classId, string _name) isActive requireDataContract requireTokenContract public returns(uint){
if (msg.sender != tokenContract)
revert();
EtheremonDataBase data = EtheremonDataBase(dataContract);
MonsterClassAcc memory class;
(class.classId, class.price, class.returnPrice, class.total, class.catchable) = data.getMonsterClass(_classId);
if (class.classId == 0 || class.catchable == false) {
revert();
}
// can not keep too much etheremon
if (data.getMonsterDexSize(_trainer) > maxDexSize)
revert();
uint requiredToken = class.price/tokenPrice;
if (_tokens < requiredToken)
revert();
// add monster
uint64 objId = data.addMonsterObj(_classId, _trainer, _name);
// generate base stat for the previous one
for (uint i=0; i < STAT_COUNT; i+= 1) {
uint8 value = getRandom(STAT_MAX, uint8(i), lastHunter) + data.getElementInArrayType(ArrayType.STAT_START, uint64(_classId), i);
data.addElementToArrayType(ArrayType.STAT_BASE, objId, value);
}
lastHunter = _trainer;
EventCatchMonster(_trainer, objId);
return requiredToken;
}
function payService(address _trainer, uint _tokens, uint32 _type, string _text, uint64 _param1, uint64 _param2, uint64 _param3, uint64 _param4, uint64 _param5, uint64 _param6) isActive requireTransformContract public returns(uint result) {
if (msg.sender != tokenContract)
revert();
TransformInterface transform = TransformInterface(transformContract);
AdventureInterface adventure = AdventureInterface(adventureContract);
if (_type == uint32(PayServiceType.FAST_HATCHING)) {
// remove hatching time
if (_tokens < fastHatchingPrice)
revert();
transform.removeHatchingTimeWithToken(_trainer);
return fastHatchingPrice;
} else if (_type == uint32(PayServiceType.RANDOM_EGG)) {
if (_tokens < buyEggPrice)
revert();
transform.buyEggWithToken(_trainer);
return buyEggPrice;
} else if (_type == uint32(PayServiceType.ADVENTURE_PRESALE)) {
adventure.placeEMONTBid(_trainer, uint8(_param1), _tokens);
return _tokens;
} else {
revert();
}
}
}
|
remove hatching time
|
function payService(address _trainer, uint _tokens, uint32 _type, string _text, uint64 _param1, uint64 _param2, uint64 _param3, uint64 _param4, uint64 _param5, uint64 _param6) isActive requireTransformContract public returns(uint result) {
if (msg.sender != tokenContract)
revert();
TransformInterface transform = TransformInterface(transformContract);
AdventureInterface adventure = AdventureInterface(adventureContract);
if (_type == uint32(PayServiceType.FAST_HATCHING)) {
if (_tokens < fastHatchingPrice)
revert();
transform.removeHatchingTimeWithToken(_trainer);
return fastHatchingPrice;
if (_tokens < buyEggPrice)
revert();
transform.buyEggWithToken(_trainer);
return buyEggPrice;
adventure.placeEMONTBid(_trainer, uint8(_param1), _tokens);
return _tokens;
revert();
}
}
| 10,333,866
|
pragma solidity ^0.6.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() 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;
}
}
// SPDX-License-Identifier: MIT
interface IERC20 {
function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
library SafeMath {
function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB321(a, b, "SafeMath: subtraction overflow");
}
function SUB321(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 MUL733(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 DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV136(a, b, "SafeMath: division by zero");
}
function DIV136(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 MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD593(a, b, "SafeMath: modulo by zero");
}
function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
library Address {
function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE193(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 FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL340(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE944(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 _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT469(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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 NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(_MSGSENDER583(), recipient, amount);
return true;
}
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(sender, recipient, amount);
_APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue));
return true;
}
function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER73(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");
_BEFORETOKENTRANSFER129(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD135(amount);
emit TRANSFER617(sender, recipient, amount);
}
function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER129(address(0), account, amount);
_totalSupply = _totalSupply.ADD135(amount);
_balances[account] = _balances[account].ADD135(amount);
emit TRANSFER617(address(0), account, amount);
}
function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER129(account, address(0), amount);
_balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB321(amount);
emit TRANSFER617(account, address(0), amount);
}
function _APPROVE319(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 APPROVAL460(owner, spender, amount);
}
function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER129(from, to, amount);
if (from == address(0)) { // When minting tokens
require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER583();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED797(address(0), msgSender);
}
function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER607() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED797(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED797(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Router01 {
function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING
function WETH181() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY85( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP722( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING
function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM21(address to) external; //inject NONSTANDARD NAMING
function SYNC269() external; //inject NONSTANDARD NAMING
function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO789() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO894(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING
}
interface IWETH {
function DEPOSIT145() external payable; //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING
}
contract CGLB is ERC20Capped, Ownable {
using SafeMath for uint;
address public UNIPAIR;
address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
bool public isRunning = false;
bool private liquidityFlag;
uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING
uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING
bytes32 public airdropRoot;
mapping (address => bool) public claimedAirdrop;
string public website = "www.cglb.fi";
constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") {
airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728;
}
function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER));
super.TRANSFER244(recipient, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(liquidityFlag);
_TRANSFER73(sender, recipient, amount);
return true;
}
function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountDAIDesired,
uint256 amountDAImin
) public payable {
require(isRunning);
require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired));
require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired));
_TRANSFER73(msg.sender, address(this), amountTokenDesired);
liquidityFlag = true;
(uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85(
address(this),
DAI,
amountTokenDesired,
amountDAIDesired,
amountTokenMin,
amountDAImin,
msg.sender,
now + 10 minutes
);
liquidityFlag = false;
//sends dust back
if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken);
if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI));
}
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING
CREATEUNISWAPPAIR64();
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING
airdropRoot = _root;
}
function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING
UNIPAIR = _pair;
}
function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING
require(UNIPAIR == address(0), "Token: pool already created");
UNIPAIR = UNIFACTORY.CREATEPAIR614(
DAI,
address(this)
);
}
function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 el;
bytes32 h = hash;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
el := mload(add(proof, i))
}
if (h < el) {
h = keccak256(abi.encodePacked(h, el));
} else {
h = keccak256(abi.encodePacked(el, h));
}
}
return h == root;
}
function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING
require(!claimedAirdrop[msg.sender]);
bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount));
require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof");
claimedAirdrop[msg.sender] = true;
_MINT517(msg.sender, amount);
}
function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING
uint balance = IERC20(token).BALANCEOF616(address(this));
require(IERC20(token).TRANSFER244(msg.sender, balance));
}
}
|
inject NONSTANDARD NAMING
|
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
| 1,820,561
|
./partial_match/1/0xc22C9A28A93AeBBB88047e390A008A59b8B7EfD5/sources/ArtBurn.sol
|
Returns the total amount of tokens stored in the given collection./
|
function collectionSupply(uint collectionId) external view returns (uint256) {
return _collectionTokens[collectionId].length();
}
| 15,764,818
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
/**
* @dev Checks if msg.sender is in whitelist.
*/
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
/**
* @dev Transfer ownership of The AO to new address
* @param _theAO The new address to be transferred
*/
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
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 {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/**
* @title TAOCurrency
*/
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
}
/**
* @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 `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title TAO
*/
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
/**
* 0 = TAO
* 1 = Name
*/
uint8 public typeId;
/**
* @dev Constructor function
*/
constructor (string _name,
address _originId,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
/**
* @dev Checks if calling address is Vault contract
*/
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
/**
* @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient`
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
/**
* @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient`
* @param _erc20TokenAddress The address of ERC20 Token
* @param _recipient The recipient address
* @param _amount The amount to transfer
* @return true on success
*/
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
/**
* @title Position
*/
contract Position is TheAO {
using SafeMath for uint256;
// Public variables of the token
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 Position Token
mapping (address => bool) public receivedToken;
// Mapping from Name ID to its total available balance
mapping (address => uint256) public balanceOf;
// Mapping from Name's TAO ID to its staked amount
mapping (address => mapping(address => uint256)) public taoStakedBalance;
// Mapping from TAO ID to its total staked amount
mapping (address => uint256) public totalTAOStakedBalance;
// 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
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply; // Update total supply
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // 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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId`
* @param _nameId Address to receive the tokens
* @return true on success
*/
function mintToken(address _nameId) public inWhitelist returns (bool) {
// Make sure _nameId has not received Position Token
require (receivedToken[_nameId] == false);
receivedToken[_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 view returns (uint256) {
return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]);
}
/**
* @dev Stake `_value` tokens 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 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
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
/**
* @dev Unstake `_value` tokens 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 returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough
require (totalTAOStakedBalance[_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
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value);
balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance
emit Unstake(_nameId, _taoId, _value);
return true;
}
}
/**
* @title NameTAOLookup
*
*/
contract NameTAOLookup is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
struct NameTAOInfo {
string name;
address nameTAOAddress;
string parentName;
uint256 typeId; // 0 = TAO. 1 = Name
}
uint256 public internalId;
uint256 public totalNames;
uint256 public totalTAOs;
mapping (uint256 => NameTAOInfo) internal nameTAOInfos;
mapping (bytes32 => uint256) internal internalIdLookup;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
}
/**
* @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 calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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 taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a name exist in the list
* @param _name The name to be checked
* @return true if yes, false otherwise
*/
function isExist(string _name) public view returns (bool) {
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
return (internalIdLookup[_nameKey] > 0);
}
/**
* @dev Add a new NameTAOInfo
* @param _name The name of the Name/TAO
* @param _nameTAOAddress The address of the Name/TAO
* @param _parentName The parent name of the Name/TAO
* @param _typeId If TAO = 0. Name = 1
* @return true on success
*/
function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) {
require (bytes(_name).length > 0);
require (_nameTAOAddress != address(0));
require (bytes(_parentName).length > 0);
require (_typeId == 0 || _typeId == 1);
require (!isExist(_name));
internalId++;
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
internalIdLookup[_nameKey] = internalId;
NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId];
_nameTAOInfo.name = _name;
_nameTAOInfo.nameTAOAddress = _nameTAOAddress;
_nameTAOInfo.parentName = _parentName;
_nameTAOInfo.typeId = _typeId;
if (_typeId == 0) {
totalTAOs++;
} else {
totalNames++;
}
return true;
}
/**
* @dev Get the NameTAOInfo given a name
* @param _name The name to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByName(string _name) public view returns (string, address, string, uint256) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Get the NameTAOInfo given an ID
* @param _internalId The internal ID to be queried
* @return the name of Name/TAO
* @return the address of Name/TAO
* @return the parent name of Name/TAO
* @return type ID. 0 = TAO. 1 = Name
*/
function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) {
require (nameTAOInfos[_internalId].nameTAOAddress != address(0));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId];
return (
_nameTAOInfo.name,
_nameTAOInfo.nameTAOAddress,
_nameTAOInfo.parentName,
_nameTAOInfo.typeId
);
}
/**
* @dev Return the nameTAOAddress given a _name
* @param _name The name to be queried
* @return the nameTAOAddress of the name
*/
function getAddressByName(string _name) public view returns (address) {
require (isExist(_name));
bytes32 _nameKey = keccak256(abi.encodePacked(_name));
NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]];
return _nameTAOInfo.nameTAOAddress;
}
}
/**
* @title NamePublicKey
*/
contract NamePublicKey {
using SafeMath for uint256;
address public nameFactoryAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
struct PublicKey {
bool created;
address defaultKey;
address[] keys;
}
// Mapping from nameId to its PublicKey
mapping (address => PublicKey) internal publicKeys;
// Event to be broadcasted to public when a publicKey is added to a Name
event AddKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is removed from a Name
event RemoveKey(address indexed nameId, address publicKey, uint256 nonce);
// Event to be broadcasted to public when a publicKey is set as default for a Name
event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress);
_;
}
/**
* @dev Check if `_nameId` is a Name
*/
modifier isName(address _nameId) {
require (AOLibrary.isName(_nameId));
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name ID exist in the list of Public Keys
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return publicKeys[_id].created;
}
/**
* @dev Store the PublicKey info for a Name
* @param _id The ID of the Name
* @param _defaultKey The default public key for this Name
* @return true on success
*/
function add(address _id, address _defaultKey)
public
isName(_id)
onlyFactory returns (bool) {
require (!isExist(_id));
require (_defaultKey != address(0));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.created = true;
_publicKey.defaultKey = _defaultKey;
_publicKey.keys.push(_defaultKey);
return true;
}
/**
* @dev Get total publicKeys count for a Name
* @param _id The ID of the Name
* @return total publicKeys count
*/
function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) {
require (isExist(_id));
return publicKeys[_id].keys.length;
}
/**
* @dev Check whether or not a publicKey exist in the list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to check
* @return true if yes. false otherwise
*/
function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) {
require (isExist(_id));
require (_key != address(0));
PublicKey memory _publicKey = publicKeys[_id];
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
return true;
}
}
return false;
}
/**
* @dev Add publicKey to list for a Name
* @param _id The ID of the Name
* @param _key The publicKey to be added
*/
function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (!isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.keys.push(_key);
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit AddKey(_id, _key, _nonce);
}
/**
* @dev Get default public key of a Name
* @param _id The ID of the Name
* @return the default public key
*/
function getDefaultKey(address _id) public isName(_id) view returns (address) {
require (isExist(_id));
return publicKeys[_id].defaultKey;
}
/**
* @dev Get list of publicKeys of a Name
* @param _id The ID of the Name
* @param _from The starting index
* @param _to The ending index
* @return list of publicKeys
*/
function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) {
require (isExist(_id));
require (_from >= 0 && _to >= _from);
PublicKey memory _publicKey = publicKeys[_id];
require (_publicKey.keys.length > 0);
address[] memory _keys = new address[](_to.sub(_from).add(1));
if (_to > _publicKey.keys.length.sub(1)) {
_to = _publicKey.keys.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_keys[i.sub(_from)] = _publicKey.keys[i];
}
return _keys;
}
/**
* @dev Remove publicKey from the list
* @param _id The ID of the Name
* @param _key The publicKey to be removed
*/
function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _key));
PublicKey storage _publicKey = publicKeys[_id];
// Can't remove default key
require (_key != _publicKey.defaultKey);
require (_publicKey.keys.length > 1);
for (uint256 i = 0; i < _publicKey.keys.length; i++) {
if (_publicKey.keys[i] == _key) {
delete _publicKey.keys[i];
_publicKey.keys.length--;
uint256 _nonce = _nameFactory.incrementNonce(_id);
break;
}
}
require (_nonce > 0);
emit RemoveKey(_id, _key, _nonce);
}
/**
* @dev Set a publicKey as the default for a Name
* @param _id The ID of the Name
* @param _defaultKey The defaultKey to be set
* @param _signatureV The V part of the signature for this update
* @param _signatureR The R part of the signature for this update
* @param _signatureS The S part of the signature for this update
*/
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) {
require (isExist(_id));
require (isKeyExist(_id, _defaultKey));
bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
PublicKey storage _publicKey = publicKeys[_id];
_publicKey.defaultKey = _defaultKey;
uint256 _nonce = _nameFactory.incrementNonce(_id);
require (_nonce > 0);
emit SetDefaultKey(_id, _defaultKey, _nonce);
}
}
/**
* @title NameFactory
*
* The purpose of this contract is to allow node to create Name
*/
contract NameFactory is TheAO {
using SafeMath for uint256;
address public positionAddress;
address public nameTAOVaultAddress;
address public nameTAOLookupAddress;
address public namePublicKeyAddress;
Position internal _position;
NameTAOLookup internal _nameTAOLookup;
NameTAOPosition internal _nameTAOPosition;
NamePublicKey internal _namePublicKey;
address[] internal names;
// Mapping from eth address to Name ID
mapping (address => address) public ethAddressToNameId;
// Mapping from Name ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when a Name is created
event CreateName(address indexed ethAddress, address nameId, uint256 index, string name);
/**
* @dev Constructor function
*/
constructor(address _positionAddress, address _nameTAOVaultAddress) public {
positionAddress = _positionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_position = Position(positionAddress);
}
/**
* @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 Checks if calling address can update Name's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress);
_;
}
/***** 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 NameTAOLookup Address
* @param _nameTAOLookupAddress The address of NameTAOLookup
*/
function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO {
require (_nameTAOLookupAddress != address(0));
nameTAOLookupAddress = _nameTAOLookupAddress;
_nameTAOLookup = NameTAOLookup(nameTAOLookupAddress);
}
/**
* @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;
_nameTAOPosition = NameTAOPosition(nameTAOPositionAddress);
}
/**
* @dev The AO set the NamePublicKey Address
* @param _namePublicKeyAddress The address of NamePublicKey
*/
function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO {
require (_namePublicKeyAddress != address(0));
namePublicKeyAddress = _namePublicKeyAddress;
_namePublicKey = NamePublicKey(namePublicKeyAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a Name
* @param _nameId The ID of the Name
* @return current nonce
*/
function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) {
// Check if _nameId exist
require (nonces[_nameId] > 0);
nonces[_nameId]++;
return nonces[_nameId];
}
/**
* @dev Create a Name
* @param _name The name of the Name
* @param _datHash The datHash to this Name's profile
* @param _database The database for this Name
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this Name
*/
function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
// Only one Name per ETH address
require (ethAddressToNameId[msg.sender] == address(0));
// The address is the Name ID (which is also a TAO ID)
address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[nameId]++;
ethAddressToNameId[msg.sender] = nameId;
// Store the name lookup information
require (_nameTAOLookup.add(_name, nameId, 'human', 1));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(nameId, nameId, nameId, nameId));
// Store the public key information
require (_namePublicKey.add(nameId, msg.sender));
names.push(nameId);
// Need to mint Position token for this Name
require (_position.mintToken(nameId));
emit CreateName(msg.sender, nameId, names.length.sub(1), _name);
}
/**
* @dev Get Name information
* @param _nameId The ID of the Name to be queried
* @return The name of the Name
* @return The originId of the Name (in this case, it's the creator node's ETH address)
* @return The datHash of the Name
* @return The database of the Name
* @return The keyValue of the Name
* @return The contentId of the Name
* @return The typeId of the Name
*/
function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) {
Name _name = Name(_nameId);
return (
_name.name(),
_name.originId(),
_name.datHash(),
_name.database(),
_name.keyValue(),
_name.contentId(),
_name.typeId()
);
}
/**
* @dev Get total Names count
* @return total Names count
*/
function getTotalNamesCount() public view returns (uint256) {
return names.length;
}
/**
* @dev Get list of Name IDs
* @param _from The starting index
* @param _to The ending index
* @return list of Name IDs
*/
function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from);
require (names.length > 0);
address[] memory _names = new address[](_to.sub(_from).add(1));
if (_to > names.length.sub(1)) {
_to = names.length.sub(1);
}
for (uint256 i = _from; i <= _to; i++) {
_names[i.sub(_from)] = names[i];
}
return _names;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be Name's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The name of the Name
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
*/
function validateNameSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public view returns (bool) {
require (_nameTAOLookup.isExist(_name));
address _nameId = _nameTAOLookup.getAddressByName(_name);
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_validateAddress != address(0)) {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _validateAddress &&
_namePublicKey.isKeyExist(_nameId, _validateAddress)
);
} else {
return (
_nonce == nonces[_nameId].add(1) &&
_signatureAddress == _namePublicKey.getDefaultKey(_nameId)
);
}
}
}
/**
* @title AOStringSetting
*
* This contract stores all AO string setting variables
*/
contract AOStringSetting is TheAO {
// Mapping from settingId to it's actual string value
mapping (uint256 => string) public settingValue;
// Mapping from settingId to it's potential string value that is at pending state
mapping (uint256 => string) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The string value to be set
*/
function setPendingValue(uint256 _settingId, string _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
string memory _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBytesSetting
*
* This contract stores all AO bytes32 setting variables
*/
contract AOBytesSetting is TheAO {
// Mapping from settingId to it's actual bytes32 value
mapping (uint256 => bytes32) public settingValue;
// Mapping from settingId to it's potential bytes32 value that is at pending state
mapping (uint256 => bytes32) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bytes32 value to be set
*/
function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bytes32 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOAddressSetting
*
* This contract stores all AO address setting variables
*/
contract AOAddressSetting is TheAO {
// Mapping from settingId to it's actual address value
mapping (uint256 => address) public settingValue;
// Mapping from settingId to it's potential address value that is at pending state
mapping (uint256 => address) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The address value to be set
*/
function setPendingValue(uint256 _settingId, address _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
address _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOBoolSetting
*
* This contract stores all AO bool setting variables
*/
contract AOBoolSetting is TheAO {
// Mapping from settingId to it's actual bool value
mapping (uint256 => bool) public settingValue;
// Mapping from settingId to it's potential bool value that is at pending state
mapping (uint256 => bool) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The bool value to be set
*/
function setPendingValue(uint256 _settingId, bool _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
bool _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOUintSetting
*
* This contract stores all AO uint256 setting variables
*/
contract AOUintSetting is TheAO {
// Mapping from settingId to it's actual uint256 value
mapping (uint256 => uint256) public settingValue;
// Mapping from settingId to it's potential uint256 value that is at pending state
mapping (uint256 => uint256) public pendingValue;
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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;
}
/***** PUBLIC METHODS *****/
/**
* @dev Set pending value
* @param _settingId The ID of the setting
* @param _value The uint256 value to be set
*/
function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist {
pendingValue[_settingId] = _value;
}
/**
* @dev Move value from pending to setting
* @param _settingId The ID of the setting
*/
function movePendingToSetting(uint256 _settingId) public inWhitelist {
uint256 _tempValue = pendingValue[_settingId];
delete pendingValue[_settingId];
settingValue[_settingId] = _tempValue;
}
}
/**
* @title AOSettingAttribute
*
* This contract stores all AO setting data/state
*/
contract AOSettingAttribute is TheAO {
NameTAOPosition internal _nameTAOPosition;
struct SettingData {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created the setting
address creatorTAOId; // The taoId that created the setting
address associatedTAOId; // The taoId that the setting affects
string settingName; // The human-readable name of the setting
/**
* 1 => uint256
* 2 => bool
* 3 => address
* 4 => bytes32
* 5 => string (catch all)
*/
uint8 settingType;
bool pendingCreate; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
string settingDataJSON; // Catch-all
}
struct SettingState {
uint256 settingId; // Identifier of this setting
bool pendingUpdate; // State when setting is in process of being updated
address updateAdvocateNameId; // The nameId of the Advocate that performed the update
/**
* A child of the associatedTAOId with the update Logos.
* This tells the setting contract that there is a proposal TAO that is a Child TAO
* of the associated TAO, which will be responsible for deciding if the update to the
* setting is accepted or rejected.
*/
address proposalTAOId;
/**
* Signature of the proposalTAOId and update value by the associatedTAOId
* Advocate's Name's address.
*/
string updateSignature;
/**
* The proposalTAOId moves here when setting value changes successfully
*/
address lastUpdateTAOId;
string settingStateJSON; // Catch-all
}
struct SettingDeprecation {
uint256 settingId; // Identifier of this setting
address creatorNameId; // The nameId that created this deprecation
address creatorTAOId; // The taoId that created this deprecation
address associatedTAOId; // The taoId that the setting affects
bool pendingDeprecated; // State when associatedTAOId has not accepted setting
bool locked; // State when pending anything (cannot change if locked)
bool rejected; // State when associatedTAOId rejected this setting
bool migrated; // State when this setting is fully migrated
// holds the pending new settingId value when a deprecation is set
uint256 pendingNewSettingId;
// holds the new settingId that has been approved by associatedTAOId
uint256 newSettingId;
// holds the pending new contract address for this setting
address pendingNewSettingContractAddress;
// holds the new contract address for this setting
address newSettingContractAddress;
}
struct AssociatedTAOSetting {
bytes32 associatedTAOSettingId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSetting {
bytes32 creatorTAOSettingId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
struct AssociatedTAOSettingDeprecation {
bytes32 associatedTAOSettingDeprecationId; // Identifier
address associatedTAOId; // The TAO ID that the setting is associated to
uint256 settingId; // The Setting ID that is associated with the TAO ID
}
struct CreatorTAOSettingDeprecation {
bytes32 creatorTAOSettingDeprecationId; // Identifier
address creatorTAOId; // The TAO ID that the setting was created from
uint256 settingId; // The Setting ID created from the TAO ID
}
// Mapping from settingId to it's data
mapping (uint256 => SettingData) internal settingDatas;
// Mapping from settingId to it's state
mapping (uint256 => SettingState) internal settingStates;
// Mapping from settingId to it's deprecation info
mapping (uint256 => SettingDeprecation) internal settingDeprecations;
// Mapping from associatedTAOSettingId to AssociatedTAOSetting
mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings;
// Mapping from creatorTAOSettingId to CreatorTAOSetting
mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings;
// Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation
mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations;
// Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation
mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations;
/**
* @dev Constructor function
*/
constructor(address _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @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));
_;
}
/***** 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 Add setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return The ID of the "Associated" setting
* @return The ID of the "Creator" setting
*/
function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) {
// Store setting data/state
require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData));
// Store the associatedTAOSetting info
bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
_associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId;
_associatedTAOSetting.associatedTAOId = _associatedTAOId;
_associatedTAOSetting.settingId = _settingId;
// Store the creatorTAOSetting info
bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
_creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId;
_creatorTAOSetting.creatorTAOId = _creatorTAOId;
_creatorTAOSetting.settingId = _settingId;
return (_associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Get Setting Data of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) {
SettingData memory _settingData = settingDatas[_settingId];
return (
_settingData.settingId,
_settingData.creatorNameId,
_settingData.creatorTAOId,
_settingData.associatedTAOId,
_settingData.settingName,
_settingData.settingType,
_settingData.pendingCreate,
_settingData.locked,
_settingData.rejected,
_settingData.settingDataJSON
);
}
/**
* @dev Get Associated TAO Setting info
* @param _associatedTAOSettingId The ID of the associated tao setting
*/
function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) {
AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId];
return (
_associatedTAOSetting.associatedTAOSettingId,
_associatedTAOSetting.associatedTAOId,
_associatedTAOSetting.settingId
);
}
/**
* @dev Get Creator TAO Setting info
* @param _creatorTAOSettingId The ID of the creator tao setting
*/
function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) {
CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId];
return (
_creatorTAOSetting.creatorTAOSettingId,
_creatorTAOSetting.creatorTAOId,
_creatorTAOSetting.settingId
);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingData.locked = false;
} else {
// Reject the setting
_settingData.pendingCreate = false;
_settingData.rejected = true;
}
return true;
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == true &&
_settingData.locked == false &&
_settingData.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId)
);
// Update the setting data
_settingData.pendingCreate = false;
_settingData.locked = true;
return true;
}
/**
* @dev Store setting update data
* @param _settingId The ID of the setting to be updated
* @param _settingType The type of this setting
* @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData memory _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.settingType == _settingType &&
_settingData.pendingCreate == false &&
_settingData.locked == true &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) &&
bytes(_updateSignature).length > 0
);
// Make sure setting is not in the middle of updating
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.pendingUpdate == false);
// Make sure setting is not yet deprecated
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
if (_settingDeprecation.settingId == _settingId) {
require (_settingDeprecation.migrated == false);
}
// Store the SettingState data
_settingState.pendingUpdate = true;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
_settingState.proposalTAOId = _proposalTAOId;
_settingState.updateSignature = _updateSignature;
_settingState.settingStateJSON = _extraData;
return true;
}
/**
* @dev Get setting state
* @param _settingId The ID of the setting
*/
function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) {
SettingState memory _settingState = settingStates[_settingId];
return (
_settingState.settingId,
_settingState.pendingUpdate,
_settingState.updateAdvocateNameId,
_settingState.proposalTAOId,
_settingState.updateSignature,
_settingState.lastUpdateTAOId,
_settingState.settingStateJSON
);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _proposalTAOAdvocate The advocate of the proposal TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId &&
_settingState.pendingUpdate == true &&
_proposalTAOAdvocate != address(0) &&
_proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of associatedTAOId can finalize the update
_settingData.locked = false;
} else {
// Set pendingUpdate to false
_settingState.pendingUpdate = false;
_settingState.proposalTAOId = address(0);
}
return true;
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @return true on success
*/
function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting is created
SettingData storage _settingData = settingDatas[_settingId];
require (_settingData.settingId == _settingId &&
_settingData.pendingCreate == false &&
_settingData.locked == false &&
_settingData.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId)
);
// Make sure setting update exists and needs approval
SettingState storage _settingState = settingStates[_settingId];
require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0));
// Update the setting data
_settingData.locked = true;
// Update the setting state
_settingState.pendingUpdate = false;
_settingState.updateAdvocateNameId = _associatedTAOAdvocate;
address _proposalTAOId = _settingState.proposalTAOId;
_settingState.proposalTAOId = address(0);
_settingState.lastUpdateTAOId = _proposalTAOId;
return true;
}
/**
* @dev Add setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return The ID of the "Associated" setting deprecation
* @return The ID of the "Creator" setting deprecation
*/
function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) {
require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress));
// Store the associatedTAOSettingDeprecation info
bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId));
AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId;
_associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId;
_associatedTAOSettingDeprecation.settingId = _settingId;
// Store the creatorTAOSettingDeprecation info
bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId));
CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId;
_creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId;
_creatorTAOSettingDeprecation.settingId = _settingId;
return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Get Setting Deprecation info of a setting ID
* @param _settingId The ID of the setting
*/
function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) {
SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId];
return (
_settingDeprecation.settingId,
_settingDeprecation.creatorNameId,
_settingDeprecation.creatorTAOId,
_settingDeprecation.associatedTAOId,
_settingDeprecation.pendingDeprecated,
_settingDeprecation.locked,
_settingDeprecation.rejected,
_settingDeprecation.migrated,
_settingDeprecation.pendingNewSettingId,
_settingDeprecation.newSettingId,
_settingDeprecation.pendingNewSettingContractAddress,
_settingDeprecation.newSettingContractAddress
);
}
/**
* @dev Get Associated TAO Setting Deprecation info
* @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation
*/
function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId];
return (
_associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId,
_associatedTAOSettingDeprecation.associatedTAOId,
_associatedTAOSettingDeprecation.settingId
);
}
/**
* @dev Get Creator TAO Setting Deprecation info
* @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation
*/
function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) {
CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId];
return (
_creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId,
_creatorTAOSettingDeprecation.creatorTAOId,
_creatorTAOSettingDeprecation.settingId
);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation
* @param _settingId The ID of the setting to approve
* @param _associatedTAOAdvocate The advocate of the associated TAO
* @param _approved Whether to approve or reject
* @return true on success
*/
function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == true &&
_settingDeprecation.rejected == false &&
_associatedTAOAdvocate != address(0) &&
_associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId)
);
if (_approved) {
// Unlock the setting so that advocate of creatorTAOId can finalize the creation
_settingDeprecation.locked = false;
} else {
// Reject the setting
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.rejected = true;
}
return true;
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
* @param _creatorTAOAdvocate The advocate of the creator TAO
* @return true on success
*/
function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) {
// Make sure setting exists and needs approval
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
require (_settingDeprecation.settingId == _settingId &&
_settingDeprecation.migrated == false &&
_settingDeprecation.pendingDeprecated == true &&
_settingDeprecation.locked == false &&
_settingDeprecation.rejected == false &&
_creatorTAOAdvocate != address(0) &&
_creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId)
);
// Update the setting data
_settingDeprecation.pendingDeprecated = false;
_settingDeprecation.locked = true;
_settingDeprecation.migrated = true;
uint256 _newSettingId = _settingDeprecation.pendingNewSettingId;
_settingDeprecation.pendingNewSettingId = 0;
_settingDeprecation.newSettingId = _newSettingId;
address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress;
_settingDeprecation.pendingNewSettingContractAddress = address(0);
_settingDeprecation.newSettingContractAddress = _newSettingContractAddress;
return true;
}
/**
* @dev Check if a setting exist and not rejected
* @param _settingId The ID of the setting
* @return true if exist. false otherwise
*/
function settingExist(uint256 _settingId) public view returns (bool) {
SettingData memory _settingData = settingDatas[_settingId];
return (_settingData.settingId == _settingId && _settingData.rejected == false);
}
/**
* @dev Get the latest ID of a deprecated setting, if exist
* @param _settingId The ID of the setting
* @return The latest setting ID
*/
function getLatestSettingId(uint256 _settingId) public view returns (uint256) {
(,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId);
while (_migrated && _newSettingId > 0) {
_settingId = _newSettingId;
(,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId);
}
return _settingId;
}
/***** Internal Method *****/
/**
* @dev Store setting data/state
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
* @return true on success
*/
function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) {
// Store setting data
SettingData storage _settingData = settingDatas[_settingId];
_settingData.settingId = _settingId;
_settingData.creatorNameId = _creatorNameId;
_settingData.creatorTAOId = _creatorTAOId;
_settingData.associatedTAOId = _associatedTAOId;
_settingData.settingName = _settingName;
_settingData.settingType = _settingType;
_settingData.pendingCreate = true;
_settingData.locked = true;
_settingData.settingDataJSON = _extraData;
// Store setting state
SettingState storage _settingState = settingStates[_settingId];
_settingState.settingId = _settingId;
return true;
}
/**
* @dev Store setting deprecation
* @param _settingId The ID of the setting
* @param _creatorNameId The nameId that created the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _newSettingId The new settingId value to route
* @param _newSettingContractAddress The address of the new setting contract to route
* @return true on success
*/
function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) {
// Make sure this setting exists
require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false);
// Make sure deprecation is not yet exist for this setting Id
require (settingDeprecations[_settingId].creatorNameId == address(0));
// Make sure newSettingId exists
require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false);
// Make sure the settingType matches
require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType);
// Store setting deprecation info
SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId];
_settingDeprecation.settingId = _settingId;
_settingDeprecation.creatorNameId = _creatorNameId;
_settingDeprecation.creatorTAOId = _creatorTAOId;
_settingDeprecation.associatedTAOId = _associatedTAOId;
_settingDeprecation.pendingDeprecated = true;
_settingDeprecation.locked = true;
_settingDeprecation.pendingNewSettingId = _newSettingId;
_settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress;
return true;
}
}
/**
* @title AOTokenInterface
*/
contract AOTokenInterface is TheAO, TokenERC20 {
using SafeMath for uint256;
// To differentiate denomination of AO
uint256 public powerOfTen;
/***** NETWORK TOKEN VARIABLES *****/
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public stakedBalance;
mapping (address => uint256) public escrowedBalance;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
event Stake(address indexed from, uint256 value);
event Unstake(address indexed from, uint256 value);
event Escrow(address indexed from, address indexed to, uint256 value);
event Unescrow(address indexed from, uint256 value);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
powerOfTen = 0;
decimals = 0;
}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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 Prevent/Allow target from sending & receiving tokens
* @param target Address to be frozen
* @param freeze Either to freeze it or not
*/
function freezeAccount(address target, bool freeze) public onlyTheAO {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
/**
* @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
* @param newSellPrice Price users can sell to the contract
* @param newBuyPrice Price users can buy from the contract
*/
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
* @return true on success
*/
function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
_mintToken(target, mintedAmount);
return true;
}
/**
* @dev Stake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to stake
* @return true on success
*/
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance
emit Stake(_from, _value);
return true;
}
/**
* @dev Unstake `_value` tokens on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @return true on success
*/
function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough
stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unstake(_from, _value);
return true;
}
/**
* @dev Store `_value` from `_from` to `_to` in escrow
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens to put in escrow
* @return true on success
*/
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
require (balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance
emit Escrow(_from, _to, _value);
return true;
}
/**
* @dev Create `mintedAmount` tokens and send it to `target` escrow balance
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive in escrow
*/
function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) {
escrowedBalance[target] = escrowedBalance[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Escrow(this, target, mintedAmount);
return true;
}
/**
* @dev Release escrowed `_value` from `_from`
* @param _from The address of the sender
* @param _value The amount of escrowed network tokens to be released
* @return true on success
*/
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) {
require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough
escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance
balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance
emit Unescrow(_from, _value);
return true;
}
/**
*
* @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
/**
* @dev Whitelisted address transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) {
_transfer(_from, _to, _value);
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Buy tokens from contract by sending ether
*/
function buy() public payable {
require (buyPrice > 0);
uint256 amount = msg.value.div(buyPrice);
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `amount` tokens to contract
* @param amount The amount of tokens to be sold
*/
function sell(uint256 amount) public {
require (sellPrice > 0);
address myAddress = this;
require (myAddress.balance >= amount.mul(sellPrice));
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount.mul(sellPrice));
}
/***** INTERNAL METHODS *****/
/**
* @dev Send `_value` tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
/**
* @dev Create `mintedAmount` tokens and send it to `target`
* @param target Address to receive the tokens
* @param mintedAmount The amount of tokens it will receive
*/
function _mintToken(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
}
/**
* @title AOToken
*/
contract AOToken is AOTokenInterface {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
// AO Dev Team addresses to receive Primordial/Network Tokens
address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52;
address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28;
AOSetting internal _aoSetting;
/***** PRIMORDIAL TOKEN VARIABLES *****/
uint256 public primordialTotalSupply;
uint256 public primordialTotalBought;
uint256 public primordialSellPrice;
uint256 public primordialBuyPrice;
// Total available primordial token for sale 1,125,899,906,842,620 AO+
uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620;
mapping (address => uint256) public primordialBalanceOf;
mapping (address => mapping (address => uint256)) public primordialAllowance;
// Mapping from owner's lot weighted multiplier to the amount of staked tokens
mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance;
event PrimordialTransfer(address indexed from, address indexed to, uint256 value);
event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value);
event PrimordialBurn(address indexed from, uint256 value);
event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier);
event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier);
uint256 public totalLots;
uint256 public totalBurnLots;
uint256 public totalConvertLots;
bool public networkExchangeEnded;
/**
* Stores Lot creation data (during network exchange)
*/
struct Lot {
bytes32 lotId;
uint256 multiplier; // This value is in 10^6, so 1000000 = 1
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account burns primordial token
*/
struct BurnLot {
bytes32 burnLotId;
address lotOwner;
uint256 tokenAmount;
}
/**
* Struct to store info when account converts network token to primordial token
*/
struct ConvertLot {
bytes32 convertLotId;
address lotOwner;
uint256 tokenAmount;
}
// Mapping from Lot ID to Lot object
mapping (bytes32 => Lot) internal lots;
// Mapping from Burn Lot ID to BurnLot object
mapping (bytes32 => BurnLot) internal burnLots;
// Mapping from Convert Lot ID to ConvertLot object
mapping (bytes32 => ConvertLot) internal convertLots;
// Mapping from owner to list of owned lot IDs
mapping (address => bytes32[]) internal ownedLots;
// Mapping from owner to list of owned burn lot IDs
mapping (address => bytes32[]) internal ownedBurnLots;
// Mapping from owner to list of owned convert lot IDs
mapping (address => bytes32[]) internal ownedConvertLots;
// Mapping from owner to his/her current weighted multiplier
mapping (address => uint256) internal ownerWeightedMultiplier;
// Mapping from owner to his/her max multiplier (multiplier of account's first Lot)
mapping (address => uint256) internal ownerMaxMultiplier;
// Event to be broadcasted to public when a lot is created
// multiplier value is in 10^6 to account for 6 decimal points
event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount);
// Event to be broadcasted to public when burn lot is created (when account burns primordial tokens)
event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn);
// Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens)
event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress)
AOTokenInterface(initialSupply, tokenName, tokenSymbol) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
_aoSetting = AOSetting(_aoSettingAddress);
powerOfTen = 0;
decimals = 0;
setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token
}
/**
* @dev Checks if buyer can buy primordial token
*/
modifier canBuyPrimordial(uint256 _sentAmount) {
require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange
* @param _aoDevTeam1 The first AO dev team address
* @param _aoDevTeam2 The second AO dev team address
*/
function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO {
aoDevTeam1 = _aoDevTeam1;
aoDevTeam2 = _aoDevTeam2;
}
/***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/
/**
* @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth
* @param newPrimordialSellPrice Price users can sell to the contract
* @param newPrimordialBuyPrice Price users can buy from the contract
*/
function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO {
primordialSellPrice = newPrimordialSellPrice;
primordialBuyPrice = newPrimordialBuyPrice;
}
/***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/
/**
* @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from`
* @param _from The address of the target
* @param _value The amount of Primordial tokens to stake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted balance is enough
require (primordialBalanceOf[_from] >= _value);
// Make sure the weighted multiplier is the same as account's current weighted multiplier
require (_weightedMultiplier == ownerWeightedMultiplier[_from]);
// Subtract from the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
// Add to the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value);
emit PrimordialStake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from`
* @param _from The address of the target
* @param _value The amount to unstake
* @param _weightedMultiplier The weighted multiplier of the Primordial tokens
* @return true on success
*/
function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) {
// Check if the targeted staked balance is enough
require (primordialStakedBalance[_from][_weightedMultiplier] >= _value);
// Subtract from the targeted staked balance
primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value);
// Add to the targeted balance
primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value);
emit PrimordialUnstake(_from, _value, _weightedMultiplier);
return true;
}
/**
* @dev Send `_value` primordial tokens to `_to` on behalf of `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/***** PUBLIC METHODS *****/
/***** Primordial TOKEN PUBLIC METHODS *****/
/**
* @dev Buy Primordial tokens from contract by sending ether
*/
function buyPrimordialToken() public payable canBuyPrimordial(msg.value) {
(uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value);
require (tokenAmount > 0);
// Ends network exchange if necessary
if (shouldEndNetworkExchange) {
networkExchangeEnded = true;
}
// Send the primordial token to buyer and reward AO devs
_sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender);
// Send remainder budget back to buyer if exist
if (remainderBudget > 0) {
msg.sender.transfer(remainderBudget);
}
}
/**
* @dev Send `_value` Primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) {
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(msg.sender, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Send `_value` Primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount to send
* @return true on success
*/
function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (_value <= primordialAllowance[_from][msg.sender]);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]);
Lot memory _lot = lots[_createdLotId];
// Make sure the new lot is created successfully
require (_lot.lotOwner == _to);
// Update the weighted multiplier of the recipient
ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value);
// Transfer the Primordial tokens
require (_transferPrimordialToken(_from, _to, _value));
emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @return true on success
*/
function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) {
primordialAllowance[msg.sender][_spender] = _value;
emit PrimordialApproval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approvePrimordialToken(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly
* and re-weight the account's multiplier after burn
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialToken(uint256 _value) public returns (bool success) {
require (primordialBalanceOf[msg.sender] >= _value);
require (calculateMaximumBurnAmount(msg.sender) >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value);
primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(msg.sender, _value);
emit PrimordialBurn(msg.sender, _value);
return true;
}
/**
* @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from`
* and re-weight `_from`'s multiplier after burn
* @param _from The address of sender
* @param _value The amount to burn
* @return true on success
*/
function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) {
require (primordialBalanceOf[_from] >= _value);
require (primordialAllowance[_from][msg.sender] >= _value);
require (calculateMaximumBurnAmount(_from) >= _value);
// Update `_from`'s multiplier
ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value);
primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value);
primordialTotalSupply = primordialTotalSupply.sub(_value);
// Store burn lot info
_createBurnLot(_from, _value);
emit PrimordialBurn(_from, _value);
return true;
}
/**
* @dev Return all lot IDs owned by an address
* @param _lotOwner The address of the lot owner
* @return array of lot IDs
*/
function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedLots[_lotOwner];
}
/**
* @dev Return the total lots owned by an address
* @param _lotOwner The address of the lot owner
* @return total lots owner by the address
*/
function totalLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedLots[_lotOwner].length;
}
/**
* @dev Return the lot information at a given index of the lots list of the requested owner
* @param _lotOwner The address owning the lots list to be accessed
* @param _index uint256 representing the index to be accessed of the requested lots list
* @return id of the lot
* @return The address of the lot owner
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) {
require (_index < ownedLots[_lotOwner].length);
Lot memory _lot = lots[ownedLots[_lotOwner][_index]];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return the lot information at a given ID
* @param _lotId The lot ID in question
* @return id of the lot
* @return The lot owner address
* @return multiplier of the lot in (10 ** 6)
* @return Primordial token amount in the lot
*/
function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) {
Lot memory _lot = lots[_lotId];
return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount);
}
/**
* @dev Return all Burn Lot IDs owned by an address
* @param _lotOwner The address of the burn lot owner
* @return array of Burn Lot IDs
*/
function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedBurnLots[_lotOwner];
}
/**
* @dev Return the total burn lots owned by an address
* @param _lotOwner The address of the burn lot owner
* @return total burn lots owner by the address
*/
function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedBurnLots[_lotOwner].length;
}
/**
* @dev Return the burn lot information at a given ID
* @param _burnLotId The burn lot ID in question
* @return id of the lot
* @return The address of the burn lot owner
* @return Primordial token amount in the burn lot
*/
function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) {
BurnLot memory _burnLot = burnLots[_burnLotId];
return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount);
}
/**
* @dev Return all Convert Lot IDs owned by an address
* @param _lotOwner The address of the convert lot owner
* @return array of Convert Lot IDs
*/
function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) {
return ownedConvertLots[_lotOwner];
}
/**
* @dev Return the total convert lots owned by an address
* @param _lotOwner The address of the convert lot owner
* @return total convert lots owner by the address
*/
function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) {
return ownedConvertLots[_lotOwner].length;
}
/**
* @dev Return the convert lot information at a given ID
* @param _convertLotId The convert lot ID in question
* @return id of the lot
* @return The address of the convert lot owner
* @return Primordial token amount in the convert lot
*/
function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) {
ConvertLot memory _convertLot = convertLots[_convertLotId];
return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount);
}
/**
* @dev Return the average weighted multiplier of all lots owned by an address
* @param _lotOwner The address of the lot owner
* @return the weighted multiplier of the address (in 10 ** 6)
*/
function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) {
return ownerWeightedMultiplier[_lotOwner];
}
/**
* @dev Return the max multiplier of an address
* @param _target The address to query
* @return the max multiplier of the address (in 10 ** 6)
*/
function maxMultiplierByAddress(address _target) public view returns (uint256) {
return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0;
}
/**
* @dev Calculate the primordial token multiplier, bonus network token percentage, and the
* bonus network token amount on a given lot when someone purchases primordial token
* during network exchange
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @return The multiplier in (10 ** 6)
* @return The bonus percentage
* @return The amount of network token as bonus
*/
function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
return (
AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier),
AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier),
AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier)
);
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* @param _account The address of the account
* @return The maximum primordial token amount to burn
*/
function calculateMaximumBurnAmount(address _account) public view returns (uint256) {
return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]);
}
/**
* @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens
* @param _account The address of the account
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) {
require (calculateMaximumBurnAmount(_account) >= _amountToBurn);
return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn);
}
/**
* @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token
* @param _account The address of the account
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier in (10 ** 6)
*/
function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) {
return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert);
}
/**
* @dev Convert `_value` of network tokens to primordial tokens
* and re-weight the account's multiplier after conversion
* @param _value The amount to convert
* @return true on success
*/
function convertToPrimordial(uint256 _value) public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
// Update the account's multiplier
ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value);
// Burn network token
burn(_value);
// mint primordial token
_mintPrimordialToken(msg.sender, _value);
// Store convert lot info
totalConvertLots++;
// Generate convert lot Id
bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots));
// Make sure no one owns this lot yet
require (convertLots[convertLotId].lotOwner == address(0));
ConvertLot storage convertLot = convertLots[convertLotId];
convertLot.convertLotId = convertLotId;
convertLot.lotOwner = msg.sender;
convertLot.tokenAmount = _value;
ownedConvertLots[msg.sender].push(convertLotId);
emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]);
return true;
}
/***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account
* @param _to The address of the recipient
* @param _value The amount of network tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transfer(_to, _value));
require (transferPrimordialToken(_to, _primordialValue));
return true;
}
/**
* @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of network tokens tokens to send
* @param _primordialValue The amount of Primordial tokens to send
* @return true on success
*/
function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.transferFrom(_from, _to, _value));
require (transferPrimordialTokenFrom(_from, _to, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of network tokens they can spend
* @return true on success
*/
function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.approve(_spender, _value));
require (approvePrimordialToken(_spender, _primordialValue));
return true;
}
/**
* @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it
* @param _spender The address authorized to spend
* @param _value The max amount of network tokens they can spend
* @param _primordialValue The max amount of Primordial Tokens they can spend
* @param _extraData some extra information to send to the approved contract
* @return true on success
*/
function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) {
require (super.approveAndCall(_spender, _value, _extraData));
require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burn(_value));
require (burnPrimordialToken(_primordialValue));
return true;
}
/**
* @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from`
* @param _from The address of sender
* @param _value The amount of network tokens to burn
* @param _primordialValue The amount of Primordial tokens to burn
* @return true on success
*/
function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) {
require (super.burnFrom(_from, _value));
require (burnPrimordialTokenFrom(_from, _primordialValue));
return true;
}
/***** INTERNAL METHODS *****/
/***** PRIMORDIAL TOKEN INTERNAL METHODS *****/
/**
* @dev Calculate the amount of token the buyer will receive and remaining budget if exist
* when he/she buys primordial token
* @param _budget The amount of ETH sent by buyer
* @return uint256 of the tokenAmount the buyer will receiver
* @return uint256 of the remaining budget, if exist
* @return bool whether or not the network exchange should end
*/
function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) {
// Calculate the amount of tokens
uint256 tokenAmount = _budget.div(primordialBuyPrice);
// If we need to return ETH to the buyer, in the case
// where the buyer sends more ETH than available primordial token to be purchased
uint256 remainderEth = 0;
// Make sure primordialTotalBought is not overflowing
bool shouldEndNetworkExchange = false;
if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) {
tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought);
shouldEndNetworkExchange = true;
remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice));
}
return (tokenAmount, remainderEth, shouldEndNetworkExchange);
}
/**
* @dev Actually sending the primordial token to buyer and reward AO devs accordingly
* @param tokenAmount The amount of primordial token to be sent to buyer
* @param to The recipient of the token
*/
function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal {
(uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables();
// Update primordialTotalBought
(uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount);
primordialTotalBought = primordialTotalBought.add(tokenAmount);
_createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount);
// Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus
uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier
uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR());
if (aoDevTeam1 != address(0)) {
_createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
if (aoDevTeam2 != address(0)) {
_createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2));
}
_mintToken(theAO, theAONetworkTokenBonusAmount);
}
/**
* @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account`
* during network exchange, and reward `_networkTokenBonusAmount` if exist
* @param _account Address of the lot owner
* @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot
* @param _multiplier The multiplier for this lot in (10 ** 6)
* @param _networkTokenBonusAmount The network token bonus amount
*/
function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal {
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _multiplier;
lot.lotOwner = _account;
lot.tokenAmount = _primordialTokenAmount;
ownedLots[_account].push(lotId);
ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
_mintPrimordialToken(_account, lot.tokenAmount);
_mintToken(_account, _networkTokenBonusAmount);
emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount);
}
/**
* @dev Create `mintedAmount` Primordial tokens and send it to `target`
* @param target Address to receive the Primordial tokens
* @param mintedAmount The amount of Primordial tokens it will receive
*/
function _mintPrimordialToken(address target, uint256 mintedAmount) internal {
primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount);
primordialTotalSupply = primordialTotalSupply.add(mintedAmount);
emit PrimordialTransfer(0, this, mintedAmount);
emit PrimordialTransfer(this, target, mintedAmount);
}
/**
* @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account`
* @param _account Address of lot owner
* @param _tokenAmount The amount of tokens
* @param _weightedMultiplier The multiplier of the lot (in 10^6)
* @return bytes32 of new created lot ID
*/
function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) {
require (_account != address(0));
require (_tokenAmount > 0);
totalLots++;
// Generate lotId
bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots));
// Make sure no one owns this lot yet
require (lots[lotId].lotOwner == address(0));
Lot storage lot = lots[lotId];
lot.lotId = lotId;
lot.multiplier = _weightedMultiplier;
lot.lotOwner = _account;
lot.tokenAmount = _tokenAmount;
ownedLots[_account].push(lotId);
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) {
ownerMaxMultiplier[_account] = lot.multiplier;
}
return lotId;
}
/**
* @dev Send `_value` Primordial tokens from `_from` to `_to`
* @param _from The address of sender
* @param _to The address of the recipient
* @param _value The amount to send
*/
function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) {
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough
require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]);
primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender
primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient
emit PrimordialTransfer(_from, _to, _value);
assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances);
return true;
}
/**
* @dev Store burn lot information
* @param _account The address of the account
* @param _tokenAmount The amount of primordial tokens to burn
*/
function _createBurnLot(address _account, uint256 _tokenAmount) internal {
totalBurnLots++;
// Generate burn lot Id
bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots));
// Make sure no one owns this lot yet
require (burnLots[burnLotId].lotOwner == address(0));
BurnLot storage burnLot = burnLots[burnLotId];
burnLot.burnLotId = burnLotId;
burnLot.lotOwner = _account;
burnLot.tokenAmount = _tokenAmount;
ownedBurnLots[_account].push(burnLotId);
emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]);
}
/**
* @dev Get setting variables
* @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token
* @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token
* @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus
* @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) {
(uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier');
(uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier');
(uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier');
(uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier');
return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier);
}
}
/**
* @title AOTreasury
*
* The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations
*/
contract AOTreasury is TheAO {
using SafeMath for uint256;
bool public paused;
bool public killed;
struct Denomination {
bytes8 name;
address denominationAddress;
}
// Mapping from denomination index to Denomination object
// The list is in order from lowest denomination to highest denomination
// i.e, denominations[1] is the base denomination
mapping (uint256 => Denomination) internal denominations;
// Mapping from denomination ID to index of denominations
mapping (bytes8 => uint256) internal denominationIndex;
uint256 public totalDenominations;
// Event to be broadcasted to public when a token exchange happens
event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @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 Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/**
* @dev Checks if denomination is valid
*/
modifier isValidDenomination(bytes8 denominationName) {
require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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 pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO adds denomination and the contract address associated with it
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
// Make sure the new denomination is higher than the previous
if (totalDenominations > 1) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress);
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
/**
* @dev The AO updates denomination address or activates/deactivates the denomination
* @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
* @param denominationAddress The address of the denomination token
* @return true on success
*/
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress);
if (_denominationNameIndex > 1) {
AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress);
require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get denomination info based on name
* @param denominationName The name to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) {
require (denominationName.length != 0);
require (denominationIndex[denominationName] > 0);
require (denominations[denominationIndex[denominationName]].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get denomination info by index
* @param index The index to be queried
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/**
* @dev Get base denomination info
* @return the denomination short name
* @return the denomination address
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) {
require (totalDenominations > 1);
return getDenominationByIndex(1);
}
/**
* @dev convert token from `denominationName` denomination to base denomination,
* in this case it's similar to web3.toWei() functionality
*
* Example:
* 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
* 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
* 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
*
* @param integerAmount uint256 of the integer amount to be converted
* @param fractionAmount uint256 of the frational amount to be converted
* @param denominationName bytes8 name of the token denomination
* @return uint256 converted amount in base denomination from target denomination
*/
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) {
if (denominationName.length > 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0) &&
(integerAmount > 0 || fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint8 fractionNumDigits = _numDigits(fractionAmount);
require (fractionNumDigits <= _denominationToken.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen());
if (_denominationToken.decimals() == 0) {
fractionAmount = 0;
}
return baseInteger.add(fractionAmount);
} else {
return 0;
}
}
/**
* @dev convert token from base denomination to `denominationName` denomination,
* in this case it's similar to web3.fromWei() functionality
* @param integerAmount uint256 of the base amount to be converted
* @param denominationName bytes8 name of the target token denomination
* @return uint256 of the converted integer amount in target denomination
* @return uint256 of the converted fraction amount in target denomination
*/
function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen()));
return (denominationInteger, denominationFraction);
}
/**
* @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination
* @param amount The amount of token to exchange
* @param fromDenominationName The origin denomination
* @param toDenominationName The target denomination
*/
function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress);
AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress);
require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount));
require (_toDenominationToken.mintToken(msg.sender, amount));
emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName);
}
/**
* @dev Return the highest possible denomination given a base amount
* @param amount The amount to be converted
* @return the denomination short name
* @return the denomination address
* @return the integer amount at the denomination level
* @return the fraction amount at the denomination level
* @return the denomination public name
* @return the denomination symbol
* @return the denomination num of decimals
* @return the denomination multiplier (power of ten)
*/
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_ao.name(),
_ao.symbol(),
_ao.decimals(),
_ao.powerOfTen()
);
}
/***** INTERNAL METHOD *****/
/**
* @dev count num of digits
* @param number uint256 of the nuumber to be checked
* @return uint8 num of digits
*/
function _numDigits(uint256 number) internal pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract Pathos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
contract Ethos is TAOCurrency {
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {}
}
/**
* @title TAOController
*/
contract TAOController {
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_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));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of TAO ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
}
// Store the name lookup for a Name/TAO
/**
* @title TAOFamily
*/
contract TAOFamily is TAOController {
using SafeMath for uint256;
address public taoFactoryAddress;
TAOFactory internal _taoFactory;
struct Child {
address taoId;
bool approved; // If false, then waiting for parent TAO approval
bool connected; // If false, then parent TAO want to remove this child TAO
}
struct Family {
address taoId;
address parentId; // The parent of this TAO ID (could be a Name or TAO)
uint256 childMinLogos;
mapping (uint256 => Child) children;
mapping (address => uint256) childInternalIdLookup;
uint256 totalChildren;
uint256 childInternalId;
}
mapping (address => Family) internal families;
// Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO
event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce);
// Event to be broadcasted to public when a TAO adds a child TAO
event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce);
// Event to be broadcasted to public when a TAO approves a child TAO
event ApproveChild(address indexed taoId, address childId, uint256 nonce);
// Event to be broadcasted to public when a TAO removes a child TAO
event RemoveChild(address indexed taoId, address childId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/**
* @dev Check if calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a TAO ID exist in the list of families
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return families[_id].taoId != address(0);
}
/**
* @dev Store the Family info for a TAO
* @param _id The ID of the TAO
* @param _parentId The parent ID of this TAO
* @param _childMinLogos The min required Logos to create a TAO
* @return true on success
*/
function add(address _id, address _parentId, uint256 _childMinLogos)
public
isTAO(_id)
isNameOrTAO(_parentId)
onlyFactory returns (bool) {
require (!isExist(_id));
Family storage _family = families[_id];
_family.taoId = _id;
_family.parentId = _parentId;
_family.childMinLogos = _childMinLogos;
return true;
}
/**
* @dev Get Family info given a TAO ID
* @param _id The ID of the TAO
* @return the parent ID of this TAO (could be a Name/TAO)
* @return the min required Logos to create a child TAO
* @return the total child TAOs count
*/
function getFamilyById(address _id) public view returns (address, uint256, uint256) {
require (isExist(_id));
Family memory _family = families[_id];
return (
_family.parentId,
_family.childMinLogos,
_family.totalChildren
);
}
/**
* @dev Set min required Logos to create a child from this TAO
* @param _childMinLogos The min Logos to set
* @return the nonce for this transaction
*/
function updateChildMinLogos(address _id, uint256 _childMinLogos)
public
isTAO(_id)
senderIsName()
onlyAdvocate(_id) {
require (isExist(_id));
Family storage _family = families[_id];
_family.childMinLogos = _childMinLogos;
uint256 _nonce = _taoFactory.incrementNonce(_id);
require (_nonce > 0);
emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce);
}
/**
* @dev Check if `_childId` is a child TAO of `_taoId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to check
* @return true if yes. Otherwise return false.
*/
function isChild(address _taoId, address _childId) public view returns (bool) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family memory _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
return (
_childInternalId > 0 &&
_family.children[_childInternalId].approved &&
_family.children[_childInternalId].connected &&
_childFamily.parentId == _taoId
);
}
/**
* @dev Add child TAO
* @param _taoId The TAO ID to be added to
* @param _childId The ID to be added to as child TAO
*/
function addChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
onlyFactory returns (bool) {
require (!isChild(_taoId, _childId));
Family storage _family = families[_taoId];
require (_family.childInternalIdLookup[_childId] == 0);
_family.childInternalId++;
_family.childInternalIdLookup[_childId] = _family.childInternalId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
Child storage _child = _family.children[_family.childInternalId];
_child.taoId = _childId;
// If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected
// Otherwise, child TAO needs parent TAO approval
address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId);
address _childAdvocate = _nameTAOPosition.getAdvocate(_childId);
if (_taoAdvocate == _childAdvocate) {
_family.totalChildren++;
_child.approved = true;
_child.connected = true;
Family storage _childFamily = families[_childId];
_childFamily.parentId = _taoId;
}
emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce);
return true;
}
/**
* @dev Advocate of `_taoId` approves child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be approved
*/
function approveChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isExist(_taoId) && isExist(_childId));
Family storage _family = families[_taoId];
Family storage _childFamily = families[_childId];
uint256 _childInternalId = _family.childInternalIdLookup[_childId];
require (_childInternalId > 0 &&
!_family.children[_childInternalId].approved &&
!_family.children[_childInternalId].connected
);
_family.totalChildren++;
Child storage _child = _family.children[_childInternalId];
_child.approved = true;
_child.connected = true;
_childFamily.parentId = _taoId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit ApproveChild(_taoId, _childId, _nonce);
}
/**
* @dev Advocate of `_taoId` removes child `_childId`
* @param _taoId The TAO ID to be checked
* @param _childId The child TAO ID to be removed
*/
function removeChild(address _taoId, address _childId)
public
isTAO(_taoId)
isTAO(_childId)
senderIsName()
onlyAdvocate(_taoId) {
require (isChild(_taoId, _childId));
Family storage _family = families[_taoId];
_family.totalChildren--;
Child storage _child = _family.children[_family.childInternalIdLookup[_childId]];
_child.connected = false;
_family.childInternalIdLookup[_childId] = 0;
Family storage _childFamily = families[_childId];
_childFamily.parentId = address(0);
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit RemoveChild(_taoId, _childId, _nonce);
}
/**
* @dev Get list of child TAO IDs
* @param _taoId The TAO ID to be checked
* @param _from The starting index (start from 1)
* @param _to The ending index, (max is childInternalId)
* @return list of child TAO IDs
*/
function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) {
require (isExist(_taoId));
Family storage _family = families[_taoId];
require (_from >= 1 && _to >= _from && _family.childInternalId >= _to);
address[] memory _childIds = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0);
}
return _childIds;
}
}
// Store TAO's child information
/**
* @title TAOFactory
*
* The purpose of this contract is to allow node to create TAO
*/
contract TAOFactory is TheAO, TAOController {
using SafeMath for uint256;
address[] internal taos;
address public taoFamilyAddress;
address public nameTAOVaultAddress;
address public settingTAOId;
NameTAOLookup internal _nameTAOLookup;
TAOFamily internal _taoFamily;
AOSetting internal _aoSetting;
Logos internal _logos;
// Mapping from TAO ID to its nonce
mapping (address => uint256) public nonces;
// Event to be broadcasted to public when Advocate creates a TAO
event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress)
TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
nameTAOVaultAddress = _nameTAOVaultAddress;
_nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_logos = Logos(_logosAddress);
}
/**
* @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 Checks if calling address can update TAO's nonce
*/
modifier canUpdateNonce {
require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress);
_;
}
/***** 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 TAOFamily Address
* @param _taoFamilyAddress The address of TAOFamily
*/
function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO {
require (_taoFamilyAddress != address(0));
taoFamilyAddress = _taoFamilyAddress;
_taoFamily = TAOFamily(taoFamilyAddress);
}
/**
* @dev The AO set settingTAOId (The TAO ID that holds the setting values)
* @param _settingTAOId The address of settingTAOId
*/
function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) {
settingTAOId = _settingTAOId;
}
/***** PUBLIC METHODS *****/
/**
* @dev Increment the nonce of a TAO
* @param _taoId The ID of the TAO
* @return current nonce
*/
function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) {
// Check if _taoId exist
require (nonces[_taoId] > 0);
nonces[_taoId]++;
return nonces[_taoId];
}
/**
* @dev Name creates a TAO
* @param _name The name of the TAO
* @param _datHash The datHash of this TAO
* @param _database The database for this TAO
* @param _keyValue The key/value pair to be checked on the database
* @param _contentId The contentId related to this TAO
* @param _parentId The parent of this TAO (has to be a Name or TAO)
* @param _childMinLogos The min required Logos to create a child from this TAO
*/
function createTAO(
string _name,
string _datHash,
string _database,
string _keyValue,
bytes32 _contentId,
address _parentId,
uint256 _childMinLogos
) public senderIsName() isNameOrTAO(_parentId) {
require (bytes(_name).length > 0);
require (!_nameTAOLookup.isExist(_name));
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
uint256 _parentCreateChildTAOMinLogos;
uint256 _createChildTAOMinLogos = _getSettingVariables();
if (AOLibrary.isTAO(_parentId)) {
(, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId);
}
if (_parentCreateChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos);
} else if (_createChildTAOMinLogos > 0) {
require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos);
}
// Create the TAO
address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress);
// Increment the nonce
nonces[taoId]++;
// Store the name lookup information
require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0));
// Store the Advocate/Listener/Speaker information
require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId));
require (_taoFamily.add(taoId, _parentId, _childMinLogos));
taos.push(taoId);
emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId());
if (AOLibrary.isTAO(_parentId)) {
require (_taoFamily.addChild(_parentId, taoId));
}
}
/**
* @dev Get TAO information
* @param _taoId The ID of the TAO to be queried
* @return The name of the TAO
* @return The origin Name ID that created the TAO
* @return The name of Name that created the TAO
* @return The datHash of the TAO
* @return The database of the TAO
* @return The keyValue of the TAO
* @return The contentId of the TAO
* @return The typeId of the TAO
*/
function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) {
TAO _tao = TAO(_taoId);
return (
_tao.name(),
_tao.originId(),
Name(_tao.originId()).name(),
_tao.datHash(),
_tao.database(),
_tao.keyValue(),
_tao.contentId(),
_tao.typeId()
);
}
/**
* @dev Get total TAOs count
* @return total TAOs count
*/
function getTotalTAOsCount() public view returns (uint256) {
return taos.length;
}
/**
* @dev Get list of TAO IDs
* @param _from The starting index
* @param _to The ending index
* @return list of TAO IDs
*/
function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) {
require (_from >= 0 && _to >= _from && taos.length > _to);
address[] memory _taos = new address[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_taos[i.sub(_from)] = taos[i];
}
return _taos;
}
/**
* @dev Check whether or not the signature is valid
* @param _data The signed string data
* @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1)
* @param _validateAddress The ETH address to be validated (optional)
* @param _name The Name of the TAO
* @param _signatureV The V part of the signature
* @param _signatureR The R part of the signature
* @param _signatureS The S part of the signature
* @return true if valid. false otherwise
* @return The name of the Name that created the signature
* @return The Position of the Name that created the signature.
* 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker
*/
function validateTAOSignature(
string _data,
uint256 _nonce,
address _validateAddress,
string _name,
uint8 _signatureV,
bytes32 _signatureR,
bytes32 _signatureS
) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) {
address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS);
if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) {
return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name)));
} else {
return (false, "", 0);
}
}
/***** INTERNAL METHOD *****/
/**
* @dev Check whether or not the address recovered from the signature is valid
* @param _validateAddress The ETH address to be validated (optional)
* @param _signatureAddress The address recovered from the signature
* @param _taoId The ID of the TAO
* @param _nonce The signed uint256 nonce
* @return true if valid. false otherwise
*/
function _isTAOSignatureAddressValid(
address _validateAddress,
address _signatureAddress,
address _taoId,
uint256 _nonce
) internal view returns (bool) {
if (_validateAddress != address(0)) {
return (_nonce == nonces[_taoId].add(1) &&
_signatureAddress == _validateAddress &&
_nameTAOPosition.senderIsPosition(_validateAddress, _taoId)
);
} else {
return (
_nonce == nonces[_taoId].add(1) &&
_nameTAOPosition.senderIsPosition(_signatureAddress, _taoId)
);
}
}
/**
* @dev Internal function to get the TAO Id by name
* @param _name The name of the TAO
* @return the TAO ID
*/
function _getTAOIdByName(string _name) internal view returns (address) {
return _nameTAOLookup.getAddressByName(_name);
}
/**
* @dev Get setting variables
* @return createChildTAOMinLogos The minimum required Logos to create a TAO
*/
function _getSettingVariables() internal view returns (uint256) {
(uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos');
return createChildTAOMinLogos;
}
}
/**
* @title NameTAOPosition
*/
contract NameTAOPosition is TheAO {
address public nameFactoryAddress;
address public taoFactoryAddress;
NameFactory internal _nameFactory;
TAOFactory internal _taoFactory;
struct Position {
address advocateId;
address listenerId;
address speakerId;
bool created;
}
mapping (address => Position) internal positions;
// Event to be broadcasted to public when current Advocate of TAO sets New Advocate
event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener
event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce);
// Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker
event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress) public {
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
nameTAOPositionAddress = address(this);
}
/**
* @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 calling address is Factory
*/
modifier onlyFactory {
require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress);
_;
}
/**
* @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));
_;
}
/**
* @dev Check if `_id` is a Name or a TAO
*/
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
/**
* @dev Check is msg.sender address is a Name
*/
modifier senderIsName() {
require (_nameFactory.ethAddressToNameId(msg.sender) != address(0));
_;
}
/**
* @dev Check if msg.sender is the current advocate of a Name/TAO ID
*/
modifier onlyAdvocate(address _id) {
require (senderIsAdvocate(msg.sender, _id));
_;
}
/***** 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 taoFactoryAddress Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = TAOFactory(_taoFactoryAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not a Name/TAO ID exist in the list
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return positions[_id].created;
}
/**
* @dev Check whether or not eth address is advocate of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsAdvocate(address _sender, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender));
}
/**
* @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id
* @param _sender The eth address to check
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function senderIsPosition(address _sender, address _id) public view returns (bool) {
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == address(0)) {
return false;
} else {
return (positions[_id].created &&
(positions[_id].advocateId == _nameId ||
positions[_id].listenerId == _nameId ||
positions[_id].speakerId == _nameId
)
);
}
}
/**
* @dev Check whether or not _nameId is advocate of _id
* @param _nameId The name ID to be checked
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function nameIsAdvocate(address _nameId, address _id) public view returns (bool) {
return (positions[_id].created && positions[_id].advocateId == _nameId);
}
/**
* @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO
* @param _sender The ETH address that to check
* @param _id The ID of the Name/TAO
* @return 1 if Advocate. 2 if Listener. 3 if Speaker
*/
function determinePosition(address _sender, address _id) public view returns (uint256) {
require (senderIsPosition(_sender, _id));
Position memory _position = positions[_id];
address _nameId = _nameFactory.ethAddressToNameId(_sender);
if (_nameId == _position.advocateId) {
return 1;
} else if (_nameId == _position.listenerId) {
return 2;
} else {
return 3;
}
}
/**
* @dev Add Position for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _advocateId The Advocate ID of the Name/TAO
* @param _listenerId The Listener ID of the Name/TAO
* @param _speakerId The Speaker ID of the Name/TAO
* @return true on success
*/
function add(address _id, address _advocateId, address _listenerId, address _speakerId)
public
isNameOrTAO(_id)
isName(_advocateId)
isNameOrTAO(_listenerId)
isNameOrTAO(_speakerId)
onlyFactory returns (bool) {
require (!isExist(_id));
Position storage _position = positions[_id];
_position.advocateId = _advocateId;
_position.listenerId = _listenerId;
_position.speakerId = _speakerId;
_position.created = true;
return true;
}
/**
* @dev Get Name/TAO's Position info
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
* @return the Listener ID of Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getPositionById(address _id) public view returns (address, address, address) {
require (isExist(_id));
Position memory _position = positions[_id];
return (
_position.advocateId,
_position.listenerId,
_position.speakerId
);
}
/**
* @dev Get Name/TAO's Advocate
* @param _id The ID of the Name/TAO
* @return the Advocate ID of Name/TAO
*/
function getAdvocate(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.advocateId;
}
/**
* @dev Get Name/TAO's Listener
* @param _id The ID of the Name/TAO
* @return the Listener ID of Name/TAO
*/
function getListener(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.listenerId;
}
/**
* @dev Get Name/TAO's Speaker
* @param _id The ID of the Name/TAO
* @return the Speaker ID of Name/TAO
*/
function getSpeaker(address _id) public view returns (address) {
require (isExist(_id));
Position memory _position = positions[_id];
return _position.speakerId;
}
/**
* @dev Set Advocate for a TAO
* @param _taoId The ID of the TAO
* @param _newAdvocateId The new advocate ID to be set
*/
function setAdvocate(address _taoId, address _newAdvocateId)
public
isTAO(_taoId)
isName(_newAdvocateId)
senderIsName()
onlyAdvocate(_taoId) {
Position storage _position = positions[_taoId];
address _currentAdvocateId = _position.advocateId;
_position.advocateId = _newAdvocateId;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce);
}
/**
* @dev Set Listener for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newListenerId The new listener ID to be set
*/
function setListener(address _id, address _newListenerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newListenerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Listener can only be a Name
// If _id is a TAO, then new Listener can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newListenerId));
}
Position storage _position = positions[_id];
address _currentListenerId = _position.listenerId;
_position.listenerId = _newListenerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce);
}
/**
* @dev Set Speaker for a Name/TAO
* @param _id The ID of the Name/TAO
* @param _newSpeakerId The new speaker ID to be set
*/
function setSpeaker(address _id, address _newSpeakerId)
public
isNameOrTAO(_id)
isNameOrTAO(_newSpeakerId)
senderIsName()
onlyAdvocate(_id) {
// If _id is a Name, then new Speaker can only be a Name
// If _id is a TAO, then new Speaker can be a TAO/Name
bool _isName = false;
if (AOLibrary.isName(_id)) {
_isName = true;
require (AOLibrary.isName(_newSpeakerId));
}
Position storage _position = positions[_id];
address _currentSpeakerId = _position.speakerId;
_position.speakerId = _newSpeakerId;
if (_isName) {
uint256 _nonce = _nameFactory.incrementNonce(_id);
} else {
_nonce = _taoFactory.incrementNonce(_id);
}
emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce);
}
}
/**
* @title AOSetting
*
* This contract stores all AO setting variables
*/
contract AOSetting {
address public aoSettingAttributeAddress;
address public aoUintSettingAddress;
address public aoBoolSettingAddress;
address public aoAddressSettingAddress;
address public aoBytesSettingAddress;
address public aoStringSettingAddress;
NameFactory internal _nameFactory;
NameTAOPosition internal _nameTAOPosition;
AOSettingAttribute internal _aoSettingAttribute;
AOUintSetting internal _aoUintSetting;
AOBoolSetting internal _aoBoolSetting;
AOAddressSetting internal _aoAddressSetting;
AOBytesSetting internal _aoBytesSetting;
AOStringSetting internal _aoStringSetting;
uint256 public totalSetting;
/**
* Mapping from associatedTAOId's setting name to Setting ID.
*
* Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup,
* use nested mapping to achieve the same result.
*
* The setting's name needs to be converted to bytes32 since solidity does not support mapping by string.
*/
mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup;
// Mapping from updateHashKey to it's settingId
mapping (bytes32 => uint256) public updateHashLookup;
// Event to be broadcasted to public when a setting is created and waiting for approval
event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId);
// Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId
event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
// Event to be broadcasted to public when a proposed update for a setting is created
event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId);
// Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId
event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId
event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate);
// Event to be broadcasted to public when a setting deprecation is created and waiting for approval
event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId);
// Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId
event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved);
// Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId
event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress,
address _nameTAOPositionAddress,
address _aoSettingAttributeAddress,
address _aoUintSettingAddress,
address _aoBoolSettingAddress,
address _aoAddressSettingAddress,
address _aoBytesSettingAddress,
address _aoStringSettingAddress) public {
aoSettingAttributeAddress = _aoSettingAttributeAddress;
aoUintSettingAddress = _aoUintSettingAddress;
aoBoolSettingAddress = _aoBoolSettingAddress;
aoAddressSettingAddress = _aoAddressSettingAddress;
aoBytesSettingAddress = _aoBytesSettingAddress;
aoStringSettingAddress = _aoStringSettingAddress;
_nameFactory = NameFactory(_nameFactoryAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
_aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress);
_aoUintSetting = AOUintSetting(_aoUintSettingAddress);
_aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress);
_aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress);
_aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress);
_aoStringSetting = AOStringSetting(_aoStringSettingAddress);
}
/**
* @dev Check if `_taoId` is a TAO
*/
modifier isTAO(address _taoId) {
require (AOLibrary.isTAO(_taoId));
_;
}
/**
* @dev Check if `_settingName` of `_associatedTAOId` is taken
*/
modifier settingNameNotTaken(string _settingName, address _associatedTAOId) {
require (settingNameExist(_settingName, _associatedTAOId) == false);
_;
}
/**
* @dev Check if msg.sender is the current advocate of Name ID
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** Public Methods *****/
/**
* @dev Check whether or not a setting name of an associatedTAOId exist
* @param _settingName The human-readable name of the setting
* @param _associatedTAOId The taoId that the setting affects
* @return true if yes. false otherwise
*/
function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) {
return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0);
}
/**
* @dev Advocate of _creatorTAOId adds a uint setting
* @param _settingName The human-readable name of the setting
* @param _value The uint256 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoUintSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bool setting
* @param _settingName The human-readable name of the setting
* @param _value The bool value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBoolSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds an address setting
* @param _settingName The human-readable name of the setting
* @param _value The address value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoAddressSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a bytes32 setting
* @param _settingName The human-readable name of the setting
* @param _value The bytes32 value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoBytesSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of _creatorTAOId adds a string setting
* @param _settingName The human-readable name of the setting
* @param _value The string value of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) {
// Update global variables
totalSetting++;
// Store the value as pending value
_aoStringSetting.setPendingValue(totalSetting, _value);
// Store setting creation data
_storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
}
/**
* @dev Advocate of Setting's _associatedTAOId approves setting creation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingCreation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved));
(,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId);
if (!_approved) {
// Clear the settingName from nameSettingLookup so it can be added again in the future
delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingCreation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate));
(,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new uint256 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoUintSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bool value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBoolSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new address value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoAddressSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new bytes32 value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoBytesSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed
* @param _settingId The ID of the setting to be updated
* @param _newValue The new string value for this setting
* @param _proposalTAOId The child of the associatedTAOId with the update Logos
* @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address
* @param _extraData Catch-all string value to be stored if exist
*/
function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) {
// Store the setting state data
require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData));
// Store the value as pending value
_aoStringSetting.setPendingValue(_settingId, _newValue);
// Store the update hash key lookup
updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId;
emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId);
}
/**
* @dev Advocate of Setting's proposalTAOId approves the setting update
* @param _settingId The ID of the setting to be approved
* @param _approved Whether to approve or reject
*/
function approveSettingUpdate(uint256 _settingId, bool _approved) public {
address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
(,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId);
require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved));
emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved);
}
/**
* @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingUpdate(uint256 _settingId) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate));
(,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId);
_movePendingToSetting(_settingId, _settingType);
emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate);
}
/**
* @dev Advocate of _creatorTAOId adds a setting deprecation
* @param _settingId The ID of the setting to be deprecated
* @param _newSettingId The new setting ID to route
* @param _newSettingContractAddress The new setting contract address to route
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
*/
function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) {
(bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress);
emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId);
}
/**
* @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation
* @param _settingId The ID of the setting to approve
* @param _approved Whether to approve or reject
*/
function approveSettingDeprecation(uint256 _settingId, bool _approved) public {
address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved));
(,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved);
}
/**
* @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved
* @param _settingId The ID of the setting to be finalized
*/
function finalizeSettingDeprecation(uint256 _settingId) public {
address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender);
require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate));
(,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId);
emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate);
}
/**
* @dev Get setting Id given an associatedTAOId and settingName
* @param _associatedTAOId The ID of the AssociatedTAO
* @param _settingName The name of the setting
* @return the ID of the setting
*/
function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) {
return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))];
}
/**
* @dev Get setting values by setting ID.
* Will throw error if the setting is not exist or rejected.
* @param _settingId The ID of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) {
require (_aoSettingAttribute.settingExist(_settingId));
_settingId = _aoSettingAttribute.getLatestSettingId(_settingId);
return (
_aoUintSetting.settingValue(_settingId),
_aoBoolSetting.settingValue(_settingId),
_aoAddressSetting.settingValue(_settingId),
_aoBytesSetting.settingValue(_settingId),
_aoStringSetting.settingValue(_settingId)
);
}
/**
* @dev Get setting values by taoId and settingName.
* Will throw error if the setting is not exist or rejected.
* @param _taoId The ID of the TAO
* @param _settingName The name of the setting
* @return the uint256 value of this setting ID
* @return the bool value of this setting ID
* @return the address value of this setting ID
* @return the bytes32 value of this setting ID
* @return the string value of this setting ID
*/
function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) {
return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName));
}
/***** Internal Method *****/
/**
* @dev Store setting creation data
* @param _creatorNameId The nameId that created the setting
* @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string
* @param _settingName The human-readable name of the setting
* @param _creatorTAOId The taoId that created the setting
* @param _associatedTAOId The taoId that the setting affects
* @param _extraData Catch-all string value to be stored if exist
*/
function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal {
// Make sure _settingType is in supported list
require (_settingType >= 1 && _settingType <= 5);
// Store nameSettingLookup
nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting;
// Store setting data/state
(bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData);
emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId);
}
/**
* @dev Move value of _settingId from pending variable to setting variable
* @param _settingId The ID of the setting
* @param _settingType The type of the setting
*/
function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal {
// If settingType == uint256
if (_settingType == 1) {
_aoUintSetting.movePendingToSetting(_settingId);
} else if (_settingType == 2) {
// Else if settingType == bool
_aoBoolSetting.movePendingToSetting(_settingId);
} else if (_settingType == 3) {
// Else if settingType == address
_aoAddressSetting.movePendingToSetting(_settingId);
} else if (_settingType == 4) {
// Else if settingType == bytes32
_aoBytesSetting.movePendingToSetting(_settingId);
} else {
// Else if settingType == string
_aoStringSetting.movePendingToSetting(_settingId);
}
}
}
/**
* @title AOEarning
*
* This contract stores the earning from staking/hosting content on AO
*/
contract AOEarning is TheAO {
using SafeMath for uint256;
address public settingTAOId;
address public aoSettingAddress;
address public baseDenominationAddress;
address public treasuryAddress;
address public nameFactoryAddress;
address public pathosAddress;
address public ethosAddress;
bool public paused;
bool public killed;
AOToken internal _baseAO;
AOTreasury internal _treasury;
NameFactory internal _nameFactory;
Pathos internal _pathos;
Ethos internal _ethos;
AOSetting internal _aoSetting;
// Total earning from staking content from all nodes
uint256 public totalStakeContentEarning;
// Total earning from hosting content from all nodes
uint256 public totalHostContentEarning;
// Total The AO earning
uint256 public totalTheAOEarning;
// Mapping from address to his/her earning from content that he/she staked
mapping (address => uint256) public stakeContentEarning;
// Mapping from address to his/her earning from content that he/she hosted
mapping (address => uint256) public hostContentEarning;
// Mapping from address to his/her network price earning
// i.e, when staked amount = filesize
mapping (address => uint256) public networkPriceEarning;
// Mapping from address to his/her content price earning
// i.e, when staked amount > filesize
mapping (address => uint256) public contentPriceEarning;
// Mapping from address to his/her inflation bonus
mapping (address => uint256) public inflationBonusAccrued;
struct Earning {
bytes32 purchaseId;
uint256 paymentEarning;
uint256 inflationBonus;
uint256 pathosAmount;
uint256 ethosAmount;
}
// Mapping from address to earning from staking content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public stakeEarnings;
// Mapping from address to earning from hosting content of a purchase ID
mapping (address => mapping(bytes32 => Earning)) public hostEarnings;
// Mapping from purchase ID to earning for The AO
mapping (bytes32 => Earning) public theAOEarnings;
// Mapping from stake ID to it's total earning from staking
mapping (bytes32 => uint256) public totalStakedContentStakeEarning;
// Mapping from stake ID to it's total earning from hosting
mapping (bytes32 => uint256) public totalStakedContentHostEarning;
// Mapping from stake ID to it's total earning earned by The AO
mapping (bytes32 => uint256) public totalStakedContentTheAOEarning;
// Mapping from content host ID to it's total earning
mapping (bytes32 => uint256) public totalHostContentEarningById;
// Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow
// recipientType:
// 0 => Content Creator (Stake Owner)
// 1 => Node Host
// 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
// Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content
event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when host's Name earns Ethos when a node buys a content
event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _nameFactoryAddress The address of NameFactory
* @param _pathosAddress The address of Pathos
* @param _ethosAddress The address of Ethos
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public {
settingTAOId = _settingTAOId;
aoSettingAddress = _aoSettingAddress;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
pathosAddress = _pathosAddress;
ethosAddress = _ethosAddress;
_aoSetting = AOSetting(_aoSettingAddress);
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_nameFactory = NameFactory(_nameFactoryAddress);
_pathos = Pathos(_pathosAddress);
_ethos = Ethos(_ethosAddress);
}
/**
* @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 Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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 pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Calculate the content creator/host/The AO earning when request node buys the content.
* Also at this stage, all of the earnings are stored in escrow
* @param _buyer The request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function calculateEarning(
address _buyer,
bytes32 _purchaseId,
uint256 _networkAmountStaked,
uint256 _primordialAmountStaked,
uint256 _primordialWeightedMultiplierStaked,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) public isContractActive inWhitelist returns (bool) {
// Split the payment earning between content creator and host and store them in escrow
_escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
// Calculate the inflation bonus earning for content creator/node/The AO in escrow
_escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType);
return true;
}
/**
* @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID to check
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _stakeOwner The address of the stake owner
* @param _host The address of the node that host the file
* @return true on success
*/
function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) {
// Release the earning in escrow for stake owner
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0);
// Release the earning in escrow for host
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1);
// Release the earning in escrow for The AO
_releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2);
return true;
}
/***** INTERNAL METHODS *****/
/**
* @dev Calculate the payment split for content creator/host and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal {
(uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType);
(uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning);
_escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount);
}
/**
* @dev Calculate the inflation bonus amount
* @param _networkAmountStaked The amount of network tokens at stake
* @param _primordialAmountStaked The amount of primordial tokens at stake
* @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake
* @return the bonus network amount
*/
function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR());
return _networkBonus.add(_primordialBonus);
}
/**
* @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _inflationBonusAmount The amount of inflation bonus earning
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _host The address of the host
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
*/
function _escrowInflationBonus(
bytes32 _purchaseId,
uint256 _inflationBonusAmount,
uint256 _profitPercentage,
address _stakeOwner,
address _host,
bool _isAOContentUsageType
) internal {
(, uint256 theAOCut,) = _getSettingVariables();
if (_inflationBonusAmount > 0) {
// Store how much the content creator earns in escrow
uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.inflationBonus = _stakeOwnerInflationBonus;
require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus));
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0);
// Store how much the host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus);
require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus));
emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1);
// Store how much the The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus));
emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2);
} else {
emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0);
emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1);
emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2);
}
}
/**
* @dev Release the escrowed earning for a specific purchase ID for an account
* @param _stakeId The ID of the staked content
* @param _contentHostId The ID of the hosted content
* @param _purchaseId The purchase receipt ID
* @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content
* @param _account The address of account that made the earning (content creator/host)
* @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO)
*/
function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal {
// Make sure the recipient type is valid
require (_recipientType >= 0 && _recipientType <= 2);
uint256 _paymentEarning;
uint256 _inflationBonus;
uint256 _totalEarning;
uint256 _pathosAmount;
uint256 _ethosAmount;
if (_recipientType == 0) {
Earning storage _earning = stakeEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_pathosAmount = _earning.pathosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning);
stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning);
totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the content creator/stake owner with some Pathos
require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount));
emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount);
} else if (_recipientType == 1) {
_earning = hostEarnings[_account][_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_ethosAmount = _earning.ethosAmount;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalHostContentEarning = totalHostContentEarning.add(_totalEarning);
hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning);
totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning);
totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning);
if (_buyerPaidMoreThanFileSize) {
contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning);
} else {
networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning);
}
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
// Reward the host node with some Ethos
require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount));
emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount);
} else {
_earning = theAOEarnings[_purchaseId];
_paymentEarning = _earning.paymentEarning;
_inflationBonus = _earning.inflationBonus;
_earning.paymentEarning = 0;
_earning.inflationBonus = 0;
_earning.pathosAmount = 0;
_earning.ethosAmount = 0;
_totalEarning = _paymentEarning.add(_inflationBonus);
// Update the global var settings
totalTheAOEarning = totalTheAOEarning.add(_totalEarning);
inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus);
totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning);
}
require (_baseAO.unescrowFrom(_account, _totalEarning));
emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType);
}
/**
* @dev Get setting variables
* @return inflationRate The rate to use when calculating inflation bonus
* @return theAOCut The rate to use when calculating the AO earning
* @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO
*/
function _getSettingVariables() internal view returns (uint256, uint256, uint256) {
(uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate');
(uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut');
(uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate');
return (inflationRate, theAOCut, theAOEthosEarnedRate);
}
/**
* @dev Calculate the payment split for content creator and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _stakeOwner The address of the stake owner
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @return The stake owner's earning amount
* @return The pathos earned from this transaction
*/
function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId];
_stakeEarning.purchaseId = _purchaseId;
// Store how much the content creator (stake owner) earns in escrow
// If content is AO Content Usage Type, stake owner earns 0%
// and all profit goes to the serving host node
_stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0;
// Pathos = Price X Node Share X Inflation Rate
_stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning));
emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0);
return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount);
}
/**
* @dev Calculate the payment split for host node and store them in escrow
* @param _buyer the request node address that buys the content
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _profitPercentage The content creator's profit percentage
* @param _host The address of the host node
* @param _isAOContentUsageType whether or not the content is of AO Content Usage Type
* @param _stakeOwnerEarning The stake owner's earning amount
* @return The ethos earned from this transaction
*/
function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) {
(uint256 inflationRate,,) = _getSettingVariables();
// Store how much the node host earns in escrow
Earning storage _hostEarning = hostEarnings[_host][_purchaseId];
_hostEarning.purchaseId = _purchaseId;
_hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning);
// Ethos = Price X Creator Share X Inflation Rate
_hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR());
if (_isAOContentUsageType) {
require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning));
} else {
// If not AO Content usage type, we want to mint to the host
require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning));
}
emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1);
return _hostEarning.ethosAmount;
}
/**
* @dev Calculate the earning for The AO and store them in escrow
* @param _purchaseId The ID of the purchase receipt object
* @param _totalStaked The total staked amount of the content
* @param _pathosAmount The amount of pathos earned by stake owner
* @param _ethosAmount The amount of ethos earned by host node
*/
function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal {
(,,uint256 theAOEthosEarnedRate) = _getSettingVariables();
// Store how much The AO earns in escrow
Earning storage _theAOEarning = theAOEarnings[_purchaseId];
_theAOEarning.purchaseId = _purchaseId;
// Pathos + X% of Ethos
_theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR()));
require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning));
emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2);
}
}
/**
* @title AOContent
*
* The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens
* on his/her content
*/
contract AOContent is TheAO {
using SafeMath for uint256;
uint256 public totalContents;
uint256 public totalContentHosts;
uint256 public totalStakedContents;
uint256 public totalPurchaseReceipts;
address public settingTAOId;
address public baseDenominationAddress;
address public treasuryAddress;
AOToken internal _baseAO;
AOTreasury internal _treasury;
AOEarning internal _earning;
AOSetting internal _aoSetting;
NameTAOPosition internal _nameTAOPosition;
bool public paused;
bool public killed;
struct Content {
bytes32 contentId;
address creator;
/**
* baseChallenge is the content's PUBLIC KEY
* When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY)
* so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node
* submit
*/
string baseChallenge;
uint256 fileSize;
bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content
address taoId;
bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO
uint8 updateTAOContentStateV;
bytes32 updateTAOContentStateR;
bytes32 updateTAOContentStateS;
string extraData;
}
struct StakedContent {
bytes32 stakeId;
bytes32 contentId;
address stakeOwner;
uint256 networkAmount; // total network token staked in base denomination
uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination)
uint256 primordialWeightedMultiplier;
uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000
bool active; // true if currently staked, false when unstaked
uint256 createdOnTimestamp;
}
struct ContentHost {
bytes32 contentHostId;
bytes32 stakeId;
address host;
/**
* encChallenge is the content's PUBLIC KEY unique to the host
*/
string encChallenge;
string contentDatKey;
string metadataDatKey;
}
struct PurchaseReceipt {
bytes32 purchaseId;
bytes32 contentHostId;
address buyer;
uint256 price;
uint256 amountPaidByBuyer; // total network token paid in base denomination
uint256 amountPaidByAO; // total amount paid by AO
string publicKey; // The public key provided by request node
address publicAddress; // The public address provided by request node
uint256 createdOnTimestamp;
}
// Mapping from Content index to the Content object
mapping (uint256 => Content) internal contents;
// Mapping from content ID to index of the contents list
mapping (bytes32 => uint256) internal contentIndex;
// Mapping from StakedContent index to the StakedContent object
mapping (uint256 => StakedContent) internal stakedContents;
// Mapping from stake ID to index of the stakedContents list
mapping (bytes32 => uint256) internal stakedContentIndex;
// Mapping from ContentHost index to the ContentHost object
mapping (uint256 => ContentHost) internal contentHosts;
// Mapping from content host ID to index of the contentHosts list
mapping (bytes32 => uint256) internal contentHostIndex;
// Mapping from PurchaseReceipt index to the PurchaseReceipt object
mapping (uint256 => PurchaseReceipt) internal purchaseReceipts;
// Mapping from purchase ID to index of the purchaseReceipts list
mapping (bytes32 => uint256) internal purchaseReceiptIndex;
// Mapping from buyer's content host ID to the buy ID
// To check whether or not buyer has bought/paid for a content
mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts;
// Event to be broadcasted to public when `content` is stored
event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType);
// Event to be broadcasted to public when `stakeOwner` stakes a new content
event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp);
// Event to be broadcasted to public when a node hosts a content
event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey);
// Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage
event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage);
// Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content
event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier);
// Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content
event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId);
// Event to be broadcasted to public when `stakeOwner` re-stakes an existing content
event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier);
// Event to be broadcasted to public when a request node buys a content
event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp);
// Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State
event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState);
// Event to be broadcasted to public when emergency mode is triggered
event EscapeHatch();
/**
* @dev Constructor function
* @param _settingTAOId The TAO ID that controls the setting
* @param _aoSettingAddress The address of AOSetting
* @param _baseDenominationAddress The address of AO base token
* @param _treasuryAddress The address of AOTreasury
* @param _earningAddress The address of AOEarning
* @param _nameTAOPositionAddress The address of NameTAOPosition
*/
constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public {
settingTAOId = _settingTAOId;
baseDenominationAddress = _baseDenominationAddress;
treasuryAddress = _treasuryAddress;
nameTAOPositionAddress = _nameTAOPositionAddress;
_baseAO = AOToken(_baseDenominationAddress);
_treasury = AOTreasury(_treasuryAddress);
_earning = AOEarning(_earningAddress);
_aoSetting = AOSetting(_aoSettingAddress);
_nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress);
}
/**
* @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 Checks if contract is currently active
*/
modifier isContractActive {
require (paused == false && killed == false);
_;
}
/***** 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 pauses/unpauses contract
* @param _paused Either to pause contract or not
*/
function setPaused(bool _paused) public onlyTheAO {
paused = _paused;
}
/**
* @dev The AO triggers emergency mode.
*
*/
function escapeHatch() public onlyTheAO {
require (killed == false);
killed = true;
emit EscapeHatch();
}
/**
* @dev The AO updates base denomination address
* @param _newBaseDenominationAddress The new address
*/
function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO {
require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0);
baseDenominationAddress = _newBaseDenominationAddress;
_baseAO = AOToken(baseDenominationAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
*/
function stakeAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage));
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_aoContent,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
_profitPercentage
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
*/
function stakeCreativeCommonsContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize);
(,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_creativeCommons,
address(0)
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
*/
function stakeTAOContent(
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
address _taoId)
public isContractActive {
require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0));
require (
_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize &&
_nameTAOPosition.senderIsPosition(msg.sender, _taoId)
);
(,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables();
/**
* 1. Store this content
* 2. Stake the network/primordial token on content
* 3. Add the node info that hosts this content (in this case the creator himself)
*/
_hostContent(
msg.sender,
_stakeContent(
msg.sender,
_storeContent(
msg.sender,
_baseChallenge,
_fileSize,
_contentUsageType_taoContent,
_taoId
),
_networkIntegerAmount,
_networkFractionAmount,
_denomination,
_primordialAmount,
0
),
_encChallenge,
_contentDatKey,
_metadataDatKey
);
}
/**
* @dev Set profit percentage on existing staked content
* Will throw error if this is a Creative Commons/T(AO) Content
* @param _stakeId The ID of the staked content
* @param _profitPercentage The new value to be set
*/
function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive {
require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR());
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure we are updating profit percentage for AO Content only
// Creative Commons/T(AO) Content has 0 profit percentage
require (_isAOContentUsageType(_stakedContent.contentId));
_stakedContent.profitPercentage = _profitPercentage;
emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage);
}
/**
* @dev Set extra data on existing content
* @param _contentId The ID of the content
* @param _extraData some extra information to send to the contract for a content
*/
function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure the content creator is the same as the sender
require (_content.creator == msg.sender);
_content.extraData = _extraData;
}
/**
* @dev Return content info at a given ID
* @param _contentId The ID of the content
* @return address of the creator
* @return file size of the content
* @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @return The TAO ID for this content (if this is a T(AO) Content)
* @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO
* @return The V part of signature that is used to update the TAO Content State
* @return The R part of signature that is used to update the TAO Content State
* @return The S part of signature that is used to update the TAO Content State
* @return the extra information sent to the contract when creating a content
*/
function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
Content memory _content = contents[contentIndex[_contentId]];
return (
_content.creator,
_content.fileSize,
_content.contentUsageType,
_content.taoId,
_content.taoContentState,
_content.updateTAOContentStateV,
_content.updateTAOContentStateR,
_content.updateTAOContentStateS,
_content.extraData
);
}
/**
* @dev Return content host info at a given ID
* @param _contentHostId The ID of the hosted content
* @return The ID of the staked content
* @return address of the host
* @return the dat key of the content
* @return the dat key of the content's metadata
*/
function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
return (
_contentHost.stakeId,
_contentHost.host,
_contentHost.contentDatKey,
_contentHost.metadataDatKey
);
}
/**
* @dev Return staked content information at a given ID
* @param _stakeId The ID of the staked content
* @return The ID of the content being staked
* @return address of the staked content's owner
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the profit percentage of the content
* @return status of the staked content
* @return the timestamp when the staked content was created
*/
function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
return (
_stakedContent.contentId,
_stakedContent.stakeOwner,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.active,
_stakedContent.createdOnTimestamp
);
}
/**
* @dev Unstake existing staked content and refund partial staked amount to the stake owner
* Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to
* the mininum required to pay the fileSize
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to unstake
* @param _networkFractionAmount The fraction amount of network token to unstake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to unstake
*/
function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the staked content has enough balance to unstake
require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize));
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount);
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount);
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Unstake existing staked content and refund the total staked amount to the stake owner
* @param _stakeId The ID of the staked content
*/
function unstakeContent(bytes32 _stakeId) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
// Make sure the staked content is currently active (staked) with some amounts
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
_stakedContent.active = false;
if (_stakedContent.networkAmount > 0) {
uint256 _unstakeNetworkAmount = _stakedContent.networkAmount;
_stakedContent.networkAmount = 0;
require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount));
}
if (_stakedContent.primordialAmount > 0) {
uint256 _primordialAmount = _stakedContent.primordialAmount;
uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier;
_stakedContent.primordialAmount = 0;
_stakedContent.primordialWeightedMultiplier = 0;
require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier));
}
emit UnstakeContent(_stakedContent.stakeOwner, _stakeId);
}
/**
* @dev Stake existing content with more tokens (this is to increase the price)
*
* @param _stakeId The ID of the staked content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier)
*/
function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive {
// Make sure the staked content exist
require (stakedContentIndex[_stakeId] > 0);
StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize;
// Make sure the staked content owner is the same as the sender
require (_stakedContent.stakeOwner == msg.sender);
require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0);
require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount));
// Make sure we can stake primordial token
// If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier`
// i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first
if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) {
require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier);
}
_stakedContent.active = true;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
_stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount);
require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount);
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier);
}
/**
* @dev Determine the content price hosted by a host
* @param _contentHostId The content host ID to be checked
* @return the price of the content
*/
function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) {
// Make sure content host exist
require (contentHostIndex[_contentHostId] > 0);
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]];
// Make sure content is currently staked
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
return _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
}
/**
* @dev Determine the how much the content is paid by AO given a contentHostId
* @param _contentHostId The content host ID to be checked
* @return the amount paid by AO
*/
function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) {
bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
if (_isAOContentUsageType(_contentId)) {
return 0;
} else {
return contentHostPrice(_contentHostId);
}
}
/**
* @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content
* @param _contentHostId The ID of hosted content
* @param _networkIntegerAmount The integer amount of network token to pay
* @param _networkFractionAmount The fraction amount of network token to pay
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _publicKey The public key of the request node
* @param _publicAddress The public address of the request node
*/
function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive {
// Make sure the content host exist
require (contentHostIndex[_contentHostId] > 0);
// Make sure public key is not empty
require (bytes(_publicKey).length > 0);
// Make sure public address is valid
require (_publicAddress != address(0));
ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]];
StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]];
// Make sure the content currently has stake
require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0)));
// Make sure the buyer has not bought this content previously
require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0);
// Make sure the token amount can pay for the content price
if (_isAOContentUsageType(_stakedContent.contentId)) {
require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination));
}
// Increment totalPurchaseReceipts;
totalPurchaseReceipts++;
// Generate purchaseId
bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId));
PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts];
// Make sure the node doesn't buy the same content twice
require (_purchaseReceipt.buyer == address(0));
_purchaseReceipt.purchaseId = _purchaseId;
_purchaseReceipt.contentHostId = _contentHostId;
_purchaseReceipt.buyer = msg.sender;
// Update the receipt with the correct network amount
_purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount);
_purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId);
_purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO);
_purchaseReceipt.publicKey = _publicKey;
_purchaseReceipt.publicAddress = _publicAddress;
_purchaseReceipt.createdOnTimestamp = now;
purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts;
buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId;
// Calculate content creator/host/The AO earning from this purchase and store them in escrow
require (_earning.calculateEarning(
msg.sender,
_purchaseId,
_stakedContent.networkAmount,
_stakedContent.primordialAmount,
_stakedContent.primordialWeightedMultiplier,
_stakedContent.profitPercentage,
_stakedContent.stakeOwner,
_contentHost.host,
_isAOContentUsageType(_stakedContent.contentId)
));
emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp);
}
/**
* @dev Return purchase receipt info at a given ID
* @param _purchaseId The ID of the purchased content
* @return The ID of the content host
* @return address of the buyer
* @return price of the content
* @return amount paid by AO
* @return amount paid by Buyer
* @return request node's public key
* @return request node's public address
* @return created on timestamp
*/
function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
return (
_purchaseReceipt.contentHostId,
_purchaseReceipt.buyer,
_purchaseReceipt.price,
_purchaseReceipt.amountPaidByAO,
_purchaseReceipt.amountPaidByBuyer,
_purchaseReceipt.publicKey,
_purchaseReceipt.publicAddress,
_purchaseReceipt.createdOnTimestamp
);
}
/**
* @dev Request node wants to become a distribution node after buying the content
* Also, if this transaction succeeds, contract will release all of the earnings that are
* currently in escrow for content creator/host/The AO
*/
function becomeHost(
bytes32 _purchaseId,
uint8 _baseChallengeV,
bytes32 _baseChallengeR,
bytes32 _baseChallengeS,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey
) public isContractActive {
// Make sure the purchase receipt exist
require (purchaseReceiptIndex[_purchaseId] > 0);
PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]];
bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId;
bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId;
// Make sure the purchase receipt owner is the same as the sender
require (_purchaseReceipt.buyer == msg.sender);
// Verify that the file is not tampered by validating the base challenge signature
// The signed base challenge key should match the one from content creator
Content memory _content = contents[contentIndex[_contentId]];
require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress);
_hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey);
// Release earning from escrow
require (_earning.releaseEarning(
_stakeId,
_purchaseReceipt.contentHostId,
_purchaseId,
(_purchaseReceipt.amountPaidByBuyer > _content.fileSize),
stakedContents[stakedContentIndex[_stakeId]].stakeOwner,
contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host)
);
}
/**
* @dev Update the TAO Content State of a T(AO) Content
* @param _contentId The ID of the Content
* @param _taoId The ID of the TAO that initiates the update
* @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _updateTAOContentStateV The V part of the signature for this update
* @param _updateTAOContentStateR The R part of the signature for this update
* @param _updateTAOContentStateS The S part of the signature for this update
*/
function updateTAOContentState(
bytes32 _contentId,
address _taoId,
bytes32 _taoContentState,
uint8 _updateTAOContentStateV,
bytes32 _updateTAOContentStateR,
bytes32 _updateTAOContentStateS
) public isContractActive {
// Make sure the content exist
require (contentIndex[_contentId] > 0);
require (AOLibrary.isTAO(_taoId));
(,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables();
require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO);
address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS);
Content storage _content = contents[contentIndex[_contentId]];
// Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker
require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId));
require (_content.contentUsageType == _contentUsageType_taoContent);
_content.taoContentState = _taoContentState;
_content.updateTAOContentStateV = _updateTAOContentStateV;
_content.updateTAOContentStateR = _updateTAOContentStateR;
_content.updateTAOContentStateS = _updateTAOContentStateS;
emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState);
}
/***** INTERNAL METHODS *****/
/**
* @dev Store the content information (content creation during staking)
* @param _creator the address of the content creator
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _fileSize The size of the file
* @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content
* @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content)
* @return the ID of the content
*/
function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) {
// Increment totalContents
totalContents++;
// Generate contentId
bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents));
Content storage _content = contents[totalContents];
// Make sure the node does't store the same content twice
require (_content.creator == address(0));
(,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables();
_content.contentId = _contentId;
_content.creator = _creator;
_content.baseChallenge = _baseChallenge;
_content.fileSize = _fileSize;
_content.contentUsageType = _contentUsageType;
// If this is a TAO Content
if (_contentUsageType == contentUsageType_taoContent) {
_content.taoContentState = taoContentState_submitted;
_content.taoId = _taoId;
}
contentIndex[_contentId] = totalContents;
emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType);
return _content.contentId;
}
/**
* @dev Add the distribution node info that hosts the content
* @param _host the address of the host
* @param _stakeId The ID of the staked content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
*/
function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal {
require (bytes(_encChallenge).length > 0);
require (bytes(_contentDatKey).length > 0);
require (bytes(_metadataDatKey).length > 0);
require (stakedContentIndex[_stakeId] > 0);
// Increment totalContentHosts
totalContentHosts++;
// Generate contentId
bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId));
ContentHost storage _contentHost = contentHosts[totalContentHosts];
// Make sure the node doesn't host the same content twice
require (_contentHost.host == address(0));
_contentHost.contentHostId = _contentHostId;
_contentHost.stakeId = _stakeId;
_contentHost.host = _host;
_contentHost.encChallenge = _encChallenge;
_contentHost.contentDatKey = _contentDatKey;
_contentHost.metadataDatKey = _metadataDatKey;
contentHostIndex[_contentHostId] = totalContentHosts;
emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey);
}
/**
* @dev actual staking the content
* @param _stakeOwner the address that stake the content
* @param _contentId The ID of the content
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return the newly created staked content ID
*/
function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) {
// Increment totalStakedContents
totalStakedContents++;
// Generate stakeId
bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId));
StakedContent storage _stakedContent = stakedContents[totalStakedContents];
// Make sure the node doesn't stake the same content twice
require (_stakedContent.stakeOwner == address(0));
_stakedContent.stakeId = _stakeId;
_stakedContent.contentId = _contentId;
_stakedContent.stakeOwner = _stakeOwner;
_stakedContent.profitPercentage = _profitPercentage;
_stakedContent.active = true;
_stakedContent.createdOnTimestamp = now;
stakedContentIndex[_stakeId] = totalStakedContents;
if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) {
_stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination);
require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount));
}
if (_primordialAmount > 0) {
_stakedContent.primordialAmount = _primordialAmount;
// Primordial Token is the base AO Token
_stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner);
require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier));
}
emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp);
return _stakedContent.stakeId;
}
/**
* @dev Get setting variables
* @return contentUsageType_aoContent Content Usage Type = AO Content
* @return contentUsageType_creativeCommons Content Usage Type = Creative Commons
* @return contentUsageType_taoContent Content Usage Type = T(AO) Content
* @return taoContentState_submitted TAO Content State = Submitted
* @return taoContentState_pendingReview TAO Content State = Pending Review
* @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO
*/
function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) {
(,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent');
(,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons');
(,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent');
(,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted');
(,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview');
(,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO');
return (
contentUsageType_aoContent,
contentUsageType_creativeCommons,
contentUsageType_taoContent,
taoContentState_submitted,
taoContentState_pendingReview,
taoContentState_acceptedToTAO
);
}
/**
* @dev Check whether or not the content is of AO Content Usage Type
* @param _contentId The ID of the content
* @return true if yes. false otherwise
*/
function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) {
(bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables();
return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent;
}
}
/**
* @title Name
*/
contract Name is TAO {
/**
* @dev Constructor function
*/
constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
contract Logos is TAOCurrency {
NameTAOPosition internal _nameTAOPosition;
// Mapping of a Name ID to the amount of Logos positioned by others to itself
// address is the address of nameId, not the eth public address
mapping (address => uint256) public positionFromOthers;
// Mapping of Name ID to other Name ID and the amount of Logos positioned by itself
mapping (address => mapping(address => uint256)) public positionToOthers;
// Mapping of a Name ID to the total amount of Logos positioned by itself to others
mapping (address => uint256) public totalPositionToOthers;
// Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned
mapping (address => mapping(address => uint256)) public advocatedTAOLogos;
// Mapping of a Name ID to the total amount of Logos earned from advocated TAO
mapping (address => uint256) public totalAdvocatedTAOLogos;
// Event broadcasted to public when `from` address position `value` Logos to `to`
event PositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `from` address unposition `value` Logos from `to`
event UnpositionFrom(address indexed from, address indexed to, uint256 value);
// Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId`
event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount);
// Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId`
event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount);
/**
* @dev Constructor function
*/
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress)
TAOCurrency(initialSupply, tokenName, tokenSymbol) public {
nameTAOPositionAddress = _nameTAOPositionAddress;
_nameTAOPosition = NameTAOPosition(_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));
_;
}
/**
* @dev Check if msg.sender is the current advocate of _id
*/
modifier onlyAdvocate(address _id) {
require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id));
_;
}
/***** PUBLIC METHODS *****/
/**
* @dev Get the total sum of Logos for an address
* @param _target The address to check
* @return The total sum of Logos (own + positioned + advocated TAOs)
*/
function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) {
return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]);
}
/**
* @dev `_from` Name position `_value` Logos onto `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to position
* @return true on success
*/
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't position Logos to itself
require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position
require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value);
positionFromOthers[_to] = positionFromOthers[_to].add(_value);
emit PositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance);
return true;
}
/**
* @dev `_from` Name unposition `_value` Logos from `_to` Name
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to unposition
* @return true on success
*/
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) {
require (_from != _to); // Can't unposition Logos to itself
require (positionToOthers[_from][_to] >= _value);
uint256 previousPositionToOthers = totalPositionToOthers[_from];
uint256 previousPositionFromOthers = positionFromOthers[_to];
uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]);
positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value);
totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value);
positionFromOthers[_to] = positionFromOthers[_to].sub(_value);
emit UnpositionFrom(_from, _to, _value);
assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers);
assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers);
assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance);
return true;
}
/**
* @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate
* @param _taoId The ID of the advocated TAO
* @param _amount the amount to reward
* @return true on success
*/
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) {
require (_amount > 0);
address _nameId = _nameTAOPosition.getAdvocate(_taoId);
advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount);
emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount);
return true;
}
/**
* @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId`
* @param _fromNameId The ID of the Name that sends the Logos
* @param _toNameId The ID of the Name that receives the Logos
* @param _taoId The ID of the advocated TAO
* @return true on success
*/
function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) {
require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId));
require (advocatedTAOLogos[_fromNameId][_taoId] > 0);
require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]);
uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId];
advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount);
totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount);
advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount);
totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount);
emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount);
return true;
}
}
/**
* @title AOLibrary
*/
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000
/**
* @dev Check whether or not the given TAO ID is a TAO
* @param _taoId The ID of the TAO
* @return true if yes. false otherwise
*/
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0);
}
/**
* @dev Check whether or not the given Name ID is a Name
* @param _nameId The ID of the Name
* @return true if yes. false otherwise
*/
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1);
}
/**
* @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
* @param _sender The address to check
* @param _theAO The AO address
* @param _nameTAOPositionAddress The address of NameTAOPosition
* @return true if yes, false otherwise
*/
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
/**
* @dev Return the divisor used to correctly calculate percentage.
* Percentage stored throughout AO contracts covers 4 decimals,
* so 1% is 10000, 1.25% is 12500, etc
*/
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
/**
* @dev Return the divisor used to correctly calculate multiplier.
* Multiplier stored throughout AO contracts covers 6 decimals,
* so 1 is 1000000, 0.023 is 23000, etc
*/
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
/**
* @dev Check whether or not content creator can stake a content based on the provided params
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _baseChallenge The base challenge string (PUBLIC KEY) of the content
* @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host
* @param _contentDatKey The dat key of the content
* @param _metadataDatKey The dat key of the content's metadata
* @param _fileSize The size of the file
* @param _profitPercentage The percentage of profit the stake owner's media will charge
* @return true if yes. false otherwise
*/
function canStake(address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
string _baseChallenge,
string _encChallenge,
string _contentDatKey,
string _metadataDatKey,
uint256 _fileSize,
uint256 _profitPercentage) public view returns (bool) {
return (
bytes(_baseChallenge).length > 0 &&
bytes(_encChallenge).length > 0 &&
bytes(_contentDatKey).length > 0 &&
bytes(_metadataDatKey).length > 0 &&
_fileSize > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) &&
_stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true &&
_profitPercentage <= _PERCENTAGE_DIVISOR
);
}
/**
* @dev Check whether or the requested unstake amount is valid
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @param _stakedNetworkAmount The current staked network token amount
* @param _stakedPrimordialAmount The current staked primordial token amount
* @param _stakedFileSize The file size of the staked content
* @return true if can unstake, false otherwise
*/
function canUnstakePartial(
address _treasuryAddress,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount,
uint256 _stakedNetworkAmount,
uint256 _stakedPrimordialAmount,
uint256 _stakedFileSize) public view returns (bool) {
if (
(_denomination.length > 0 &&
(_networkIntegerAmount > 0 || _networkFractionAmount > 0) &&
_stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)
) ||
_stakedPrimordialAmount < _primordialAmount ||
(
_denomination.length > 0
&& (_networkIntegerAmount > 0 || _networkFractionAmount > 0)
&& (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize)
) ||
( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize)
) {
return false;
} else {
return true;
}
}
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _isAOContentUsageType whether or not the content is of AO Content usage type
* @param _fileSize The size of the file
* @param _stakedAmount The total staked amount
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @param _primordialAmount The amount of primordial token
* @return true when the amount is sufficient, false otherwise
*/
function canStakeExisting(
address _treasuryAddress,
bool _isAOContentUsageType,
uint256 _fileSize,
uint256 _stakedAmount,
uint256 _networkIntegerAmount,
uint256 _networkFractionAmount,
bytes8 _denomination,
uint256 _primordialAmount
) public view returns (bool) {
if (_isAOContentUsageType) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize;
} else {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize;
}
}
/**
* @dev Check whether the network token is adequate to pay for existing staked content
* @param _treasuryAddress AO treasury contract address
* @param _price The price of the content
* @param _networkIntegerAmount The integer amount of the network token
* @param _networkFractionAmount The fraction amount of the network token
* @param _denomination The denomination of the the network token
* @return true when the amount is sufficient, false otherwise
*/
function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price;
}
/**
* @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _currentPrimordialBalance Account's current primordial token balance
* @param _additionalWeightedMultiplier The weighted multiplier to be added
* @param _additionalPrimordialAmount The primordial token amount to be added
* @return the new primordial weighted multiplier
*/
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedTokens.div(_totalTokens);
} else {
return _additionalWeightedMultiplier;
}
}
/**
* @dev Return the address that signed the message when a node wants to become a host
* @param _callingContractAddress the address of the calling contract
* @param _message the message that was signed
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the address that signed the TAO content state update
* @param _callingContractAddress the address of the calling contract
* @param _contentId the ID of the content
* @param _taoId the ID of the TAO
* @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState));
return ecrecover(_hash, _v, _r, _s);
}
/**
* @dev Return the staking and earning information of a stake ID
* @param _contentAddress The address of AOContent
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId);
(uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier,
totalStakeEarning,
totalHostEarning,
totalTheAOEarning
);
}
/**
* @dev Return the staking information of a stake ID
* @param _contentAddress The address of AOContent
* @param _stakeId The ID of the staked content
* @return the network base token amount staked for this content
* @return the primordial token amount staked for this content
* @return the primordial weighted multiplier of the staked content
*/
function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
(,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId);
return (
networkAmount,
primordialAmount,
primordialWeightedMultiplier
);
}
/**
* @dev Return the earning information of a stake ID
* @param _earningAddress The address of AOEarning
* @param _stakeId The ID of the staked content
* @return the total earning from staking this content
* @return the total earning from hosting this content
* @return the total The AO earning of this content
*/
function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) {
return (
AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId),
AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId)
);
}
/**
* @dev Calculate the primordial token multiplier on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Multiplier = S
* Ending Multiplier = E
* To Purchase = P
* Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting multiplier in (10 ** 6)
* @param _endingMultiplier The ending multiplier in (10 ** 6)
* @return The multiplier in (10 ** 6)
*/
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* Multiplier = (1 - (temp / T)) x (S-E)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals
* so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E)
* Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR
* Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR
* Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation
* Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)
*/
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
/**
* Since _startingMultiplier and _endingMultiplier are in 6 decimals
* Need to divide multiplier by _MULTIPLIER_DIVISOR
*/
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
/**
* @dev Calculate the bonus percentage of network token on a given lot
* Total Primordial Mintable = T
* Total Primordial Minted = M
* Starting Network Token Bonus Multiplier = Bs
* Ending Network Token Bonus Multiplier = Be
* To Purchase = P
* AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be)
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
/**
* Let temp = M + (P/2)
* B% = (1 - (temp / T)) x (Bs-Be)
*/
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
/**
* Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals
* so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be)
* B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR
* Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)
* But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR
* B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR
*/
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
/**
* @dev Calculate the bonus amount of network token on a given lot
* AO Bonus Amount = B% x P
*
* @param _purchaseAmount The amount of primordial token intended to be purchased
* @param _totalPrimordialMintable Total Primordial token intable
* @param _totalPrimordialMinted Total Primordial token minted so far
* @param _startingMultiplier The starting Network token bonus multiplier
* @param _endingMultiplier The ending Network token bonus multiplier
* @return The bonus percentage
*/
function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network token bonus amount
*/
uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkTokenBonus;
}
/**
* @dev Calculate the maximum amount of Primordial an account can burn
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _maximumMultiplier = S
* _amountToBurn = B
* B = ((S x P) - (P x M)) / S
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _maximumMultiplier The maximum multiplier of this account
* @return The maximum burn amount
*/
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
/**
* @dev Calculate the new multiplier after burning primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToBurn = B
* _newMultiplier = E
* E = (P x M) / (P - B)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToBurn The amount of primordial token to burn
* @return The new multiplier
*/
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
/**
* @dev Calculate the new multiplier after converting network token to primordial token
* _primordialBalance = P
* _currentWeightedMultiplier = M
* _amountToConvert = C
* _newMultiplier = E
* E = (P x M) / (P + C)
*
* @param _primordialBalance Account's primordial token balance
* @param _currentWeightedMultiplier Account's current weighted multiplier
* @param _amountToConvert The amount of network token to convert
* @return The new multiplier
*/
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
/**
* @dev Get TAO Currency Balances given a nameId
* @param _nameId The ID of the Name
* @param _logosAddress The address of Logos
* @param _ethosAddress The address of Ethos
* @param _pathosAddress The address of Pathos
* @return sum Logos balance of the Name ID
* @return Ethos balance of the Name ID
* @return Pathos balance of the Name ID
*/
function getTAOCurrencyBalances(
address _nameId,
address _logosAddress,
address _ethosAddress,
address _pathosAddress
) public view returns (uint256, uint256, uint256) {
return (
Logos(_logosAddress).sumBalanceOf(_nameId),
TAOCurrency(_ethosAddress).balanceOf(_nameId),
TAOCurrency(_pathosAddress).balanceOf(_nameId)
);
}
/**
* @dev Return the address that signed the data and nonce when validating signature
* @param _callingContractAddress the address of the calling contract
* @param _data the data that was signed
* @param _nonce The signed uint256 nonce
* @param _v part of the signature
* @param _r part of the signature
* @param _s part of the signature
* @return the address that signed the message
*/
function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) {
bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce));
return ecrecover(_hash, _v, _r, _s);
}
/***** Internal Methods *****/
/**
* @dev Check whether the network token and/or primordial token is adequate to pay for the filesize
* @param _treasuryAddress AO treasury contract address
* @param _networkIntegerAmount The integer amount of network token to stake
* @param _networkFractionAmount The fraction amount of network token to stake
* @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc.
* @param _primordialAmount The amount of primordial Token to stake
* @param _fileSize The size of the file
* @return true when the amount is sufficient, false otherwise
*/
function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) {
return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize;
}
}
contract Epiphany is TheAO {
string public what;
string public when;
string public why;
string public who;
address public where;
string public aSign;
string public logos;
constructor() public {
what = 'The AO';
when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.';
why = 'To Hear, See, and Speak the Human inside Humanity.';
who = 'You. Set the world, Free. – Truth';
aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf';
logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32';
}
/**
* @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));
_;
}
/***** The AO ONLY METHODS *****/
/**
* @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;
}
/**
* @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 Set `where` value
* @param _where The new value to be set
*/
function setWhere(address _where) public onlyTheAO {
where = _where;
}
}
|
Stake `_value` tokens on `_taoId` from `_nameId` _nameId The Name ID that wants to stake _taoId The TAO ID to stake _value The amount to stake return true on success/
|
function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) {
require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME);
totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value);
emit Stake(_nameId, _taoId, _value);
return true;
}
| 10,007,049
|
./full_match/44787/0xFBf4Fa7119Ebd69c8786E628acD76FE21C3F0903/sources/contracts/ERC721/EQTradableV2.sol
|
Returns if the token is for sale on the market./
|
function isForSale(uint256 tokenId) public view returns (bool forSale) {
return _forSale[tokenId];
}
| 13,258,736
|
pragma solidity ^0.7.4;pragma experimental ABIEncoderV2;
import "./ForwardingResolver.sol";
import "./profiles/StealthKeyResolver.sol";
contract ForwardingStealthKeyResolver is ForwardingResolver, StealthKeyResolver {
constructor(ENS _ens, PublicResolver _fallbackResolver) ForwardingResolver(_ens, _fallbackResolver) { }
function supportsInterface(bytes4 interfaceID) public virtual override(PublicResolver, StealthKeyResolver) pure returns(bool) {
return StealthKeyResolver.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;pragma experimental ABIEncoderV2;
import "@ensdomains/ens/contracts/ENS.sol";
import "./profiles/ABIResolver.sol";
import "./profiles/AddrResolver.sol";
import "./profiles/ContentHashResolver.sol";
import "./profiles/DNSResolver.sol";
import "./profiles/InterfaceResolver.sol";
import "./profiles/NameResolver.sol";
import "./profiles/PubkeyResolver.sol";
import "./profiles/TextResolver.sol";
import "./PublicResolver.sol";
contract ForwardingResolver is PublicResolver {
PublicResolver public fallbackResolver;
constructor(ENS _ens, PublicResolver _fallbackResolver) PublicResolver(_ens) {
fallbackResolver = _fallbackResolver;
}
//===============================AddrResolver Forwarding===============================//
function setAddr(bytes32 node, address a) override external authorised(node) {
fallbackResolver.setAddr(node, a);
}
function addr(bytes32 node) override public view returns (address payable) {
return fallbackResolver.addr(node);
}
function setAddr(bytes32 node, uint coinType, bytes memory a) override public authorised(node) {
fallbackResolver.setAddr(node, coinType, a);
}
function addr(bytes32 node, uint coinType) override public view returns(bytes memory) {
return fallbackResolver.addr(node, coinType);
}
//===============================NameResolver Forwarding===============================//
function setName(bytes32 node, string calldata name) override external authorised(node) {
fallbackResolver.setName(node, name);
}
function name(bytes32 node) override external view returns (string memory) {
return fallbackResolver.name(node);
}
//===============================PubkeyResolver Forwarding============================//
function setPubkey(bytes32 node, bytes32 x, bytes32 y) override external authorised(node) {
fallbackResolver.setPubkey(node, x, y);
}
function pubkey(bytes32 node) override external view returns (bytes32 x, bytes32 y) {
return fallbackResolver.pubkey(node);
}
//===============================ABIResolver Forwarding================================//
function setABI(bytes32 node, uint256 contentType, bytes calldata data) override external authorised(node) {
fallbackResolver.setABI(node, contentType, data);
}
function ABI(bytes32 node, uint256 contentTypes) override external view returns (uint256, bytes memory) {
return fallbackResolver.ABI(node, contentTypes);
}
//===============================TextResolver Forwarding===============================//
function setText(bytes32 node, string calldata key, string calldata value) override external authorised(node) {
fallbackResolver.setText(node, key, value);
}
function text(bytes32 node, string calldata key) override external view returns (string memory) {
return fallbackResolver.text(node, key);
}
//===============================ContentHashResolver Forwarding========================//
function setContenthash(bytes32 node, bytes calldata hash) override external authorised(node) {
fallbackResolver.setContenthash(node, hash);
}
function contenthash(bytes32 node) override external view returns (bytes memory) {
return fallbackResolver.contenthash(node);
}
//===============================DNSResolver Forwarding================================//
function setDNSRecords(bytes32 node, bytes calldata data) override external authorised(node) {
fallbackResolver.setDNSRecords(node, data);
}
function dnsRecord(bytes32 node, bytes32 name, uint16 resource) override public view returns (bytes memory) {
return fallbackResolver.dnsRecord(node, name, resource);
}
function hasDNSRecords(bytes32 node, bytes32 name) override public view returns (bool) {
return fallbackResolver.hasDNSRecords(node, name);
}
function clearDNSZone(bytes32 node) override public authorised(node) {
fallbackResolver.clearDNSZone(node);
}
function setZonehash(bytes32 node, bytes calldata hash) override external authorised(node) {
fallbackResolver.setZonehash(node, hash);
}
function zonehash(bytes32 node) override external view returns (bytes memory) {
return fallbackResolver.zonehash(node);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract StealthKeyResolver is ResolverBase {
bytes4 constant private STEALTH_KEY_INTERFACE_ID = 0x69a76591;
/// @dev Event emitted when a user updates their resolver stealth keys
event StealthKeyChanged(bytes32 indexed node, uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey);
/**
* @dev Mapping used to store two secp256k1 curve public keys useful for
* receiving stealth payments. The mapping records two keys: a viewing
* key and a spending key, which can be set and read via the `setsStealthKeys`
* and `stealthKey` methods respectively.
*
* The mapping associates the node to another mapping, which itself maps
* the public key prefix to the actual key . This scheme is used to avoid using an
* extra storage slot for the public key prefix. For a given node, the mapping
* may contain a spending key at position 0 or 1, and a viewing key at position
* 2 or 3. See the setter/getter methods for details of how these map to prefixes.
*
* For more on secp256k1 public keys and prefixes generally, see:
* https://github.com/ethereumbook/ethereumbook/blob/develop/04keys-addresses.asciidoc#generating-a-public-key
*
*/
mapping(bytes32 => mapping(uint256 => uint256)) _stealthKeys;
/**
* Sets the stealth keys associated with an ENS name, for anonymous sends.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param spendingPubKeyPrefix Prefix of the spending public key (2 or 3)
* @param spendingPubKey The public key for generating a stealth address
* @param viewingPubKeyPrefix Prefix of the viewing public key (2 or 3)
* @param viewingPubKey The public key to use for encryption
*/
function setStealthKeys(bytes32 node, uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey) external authorised(node) {
require(
(spendingPubKeyPrefix == 2 || spendingPubKeyPrefix == 3) &&
(viewingPubKeyPrefix == 2 || viewingPubKeyPrefix == 3),
"StealthKeyResolver: Invalid Prefix"
);
emit StealthKeyChanged(node, spendingPubKeyPrefix, spendingPubKey, viewingPubKeyPrefix, viewingPubKey);
// Shift the spending key prefix down by 2, making it the appropriate index of 0 or 1
spendingPubKeyPrefix -= 2;
// Ensure the opposite prefix indices are empty
delete _stealthKeys[node][1 - spendingPubKeyPrefix];
delete _stealthKeys[node][5 - viewingPubKeyPrefix];
// Set the appropriate indices to the new key values
_stealthKeys[node][spendingPubKeyPrefix] = spendingPubKey;
_stealthKeys[node][viewingPubKeyPrefix] = viewingPubKey;
}
/**
* Returns the stealth key associated with a name.
* @param node The ENS node to query.
* @return spendingPubKeyPrefix Prefix of the spending public key (2 or 3)
* @return spendingPubKey The public key for generating a stealth address
* @return viewingPubKeyPrefix Prefix of the viewing public key (2 or 3)
* @return viewingPubKey The public key to use for encryption
*/
function stealthKeys(bytes32 node) external view returns (uint256 spendingPubKeyPrefix, uint256 spendingPubKey, uint256 viewingPubKeyPrefix, uint256 viewingPubKey) {
if (_stealthKeys[node][0] != 0) {
spendingPubKeyPrefix = 2;
spendingPubKey = _stealthKeys[node][0];
} else {
spendingPubKeyPrefix = 3;
spendingPubKey = _stealthKeys[node][1];
}
if (_stealthKeys[node][2] != 0) {
viewingPubKeyPrefix = 2;
viewingPubKey = _stealthKeys[node][2];
} else {
viewingPubKeyPrefix = 3;
viewingPubKey = _stealthKeys[node][3];
}
return (spendingPubKeyPrefix, spendingPubKey, viewingPubKeyPrefix, viewingPubKey);
}
function supportsInterface(bytes4 interfaceID) public virtual override pure returns(bool) {
return interfaceID == STEALTH_KEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.0;
interface ENS {
// 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);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external virtual;
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external virtual;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external virtual returns(bytes32);
function setResolver(bytes32 node, address resolver) external virtual;
function setOwner(bytes32 node, address owner) external virtual;
function setTTL(bytes32 node, uint64 ttl) external virtual;
function setApprovalForAll(address operator, bool approved) external virtual;
function owner(bytes32 node) external virtual view returns (address);
function resolver(bytes32 node) external virtual view returns (address);
function ttl(bytes32 node) external virtual view returns (uint64);
function recordExists(bytes32 node) external virtual view returns (bool);
function isApprovedForAll(address owner, address operator) external virtual view returns (bool);
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) virtual external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) virtual external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06;
uint constant private COIN_TYPE_ETH = 60;
event AddrChanged(bytes32 indexed node, address a);
event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress);
mapping(bytes32=>mapping(uint=>bytes)) _addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param a The address to set.
*/
function setAddr(bytes32 node, address a) virtual external authorised(node) {
setAddr(node, COIN_TYPE_ETH, addressToBytes(a));
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) virtual public view returns (address payable) {
bytes memory a = addr(node, COIN_TYPE_ETH);
if(a.length == 0) {
return address(0);
}
return bytesToAddress(a);
}
function setAddr(bytes32 node, uint coinType, bytes memory a) virtual public authorised(node) {
emit AddressChanged(node, coinType, a);
if(coinType == COIN_TYPE_ETH) {
emit AddrChanged(node, bytesToAddress(a));
}
_addresses[node][coinType] = a;
}
function addr(bytes32 node, uint coinType) virtual public view returns(bytes memory) {
return _addresses[node][coinType];
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) virtual external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) virtual external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
import "@ensdomains/dnssec-oracle/contracts/RRUtils.sol";
abstract contract DNSResolver is ResolverBase {
using RRUtils for *;
using BytesUtils for bytes;
bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682;
bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c;
// DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated.
event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);
// DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted.
event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource);
// DNSZoneCleared is emitted whenever a given node's zone information is cleared.
event DNSZoneCleared(bytes32 indexed node);
// DNSZonehashChanged is emitted whenever a given node's zone hash is updated.
event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash);
// Zone hashes for the domains.
// A zone hash is an EIP-1577 content hash in binary format that should point to a
// resource containing a single zonefile.
// node => contenthash
mapping(bytes32=>bytes) private zonehashes;
// Version the mapping for each zone. This allows users who have lost
// track of their entries to effectively delete an entire zone by bumping
// the version number.
// node => version
mapping(bytes32=>uint256) private versions;
// The records themselves. Stored as binary RRSETs
// node => version => name => resource => data
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records;
// Count of number of entries for a given name. Required for DNS resolvers
// when resolving wildcards.
// node => version => name => number of records
mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount;
/**
* Set one or more DNS records. Records are supplied in wire-format.
* Records with the same node/name/resource must be supplied one after the
* other to ensure the data is updated correctly. For example, if the data
* was supplied:
* a.example.com IN A 1.2.3.4
* a.example.com IN A 5.6.7.8
* www.example.com IN CNAME a.example.com.
* then this would store the two A records for a.example.com correctly as a
* single RRSET, however if the data was supplied:
* a.example.com IN A 1.2.3.4
* www.example.com IN CNAME a.example.com.
* a.example.com IN A 5.6.7.8
* then this would store the first A record, the CNAME, then the second A
* record which would overwrite the first.
*
* @param node the namehash of the node for which to set the records
* @param data the DNS wire format records to set
*/
function setDNSRecords(bytes32 node, bytes calldata data) virtual external authorised(node) {
uint16 resource = 0;
uint256 offset = 0;
bytes memory name;
bytes memory value;
bytes32 nameHash;
// Iterate over the data to add the resource records
for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {
if (resource == 0) {
resource = iter.dnstype;
name = iter.name();
nameHash = keccak256(abi.encodePacked(name));
value = bytes(iter.rdata());
} else {
bytes memory newName = iter.name();
if (resource != iter.dnstype || !name.equals(newName)) {
setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0);
resource = iter.dnstype;
offset = iter.offset;
name = newName;
nameHash = keccak256(name);
value = bytes(iter.rdata());
}
}
}
if (name.length > 0) {
setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0);
}
}
/**
* Obtain a DNS record.
* @param node the namehash of the node for which to fetch the record
* @param name the keccak-256 hash of the fully-qualified name for which to fetch the record
* @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types
* @return the DNS record in wire format if present, otherwise empty
*/
function dnsRecord(bytes32 node, bytes32 name, uint16 resource) virtual public view returns (bytes memory) {
return records[node][versions[node]][name][resource];
}
/**
* Check if a given node has records.
* @param node the namehash of the node for which to check the records
* @param name the namehash of the node for which to check the records
*/
function hasDNSRecords(bytes32 node, bytes32 name) virtual public view returns (bool) {
return (nameEntriesCount[node][versions[node]][name] != 0);
}
/**
* Clear all information for a DNS zone.
* @param node the namehash of the node for which to clear the zone
*/
function clearDNSZone(bytes32 node) virtual public authorised(node) {
versions[node]++;
emit DNSZoneCleared(node);
}
/**
* setZonehash sets the hash for the zone.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The zonehash to set
*/
function setZonehash(bytes32 node, bytes calldata hash) virtual external authorised(node) {
bytes memory oldhash = zonehashes[node];
zonehashes[node] = hash;
emit DNSZonehashChanged(node, oldhash, hash);
}
/**
* zonehash obtains the hash for the zone.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function zonehash(bytes32 node) virtual external view returns (bytes memory) {
return zonehashes[node];
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == DNS_RECORD_INTERFACE_ID ||
interfaceID == DNS_ZONE_INTERFACE_ID ||
super.supportsInterface(interfaceID);
}
function setDNSRRSet(
bytes32 node,
bytes memory name,
uint16 resource,
bytes memory data,
uint256 offset,
uint256 size,
bool deleteRecord) internal
{
uint256 version = versions[node];
bytes32 nameHash = keccak256(name);
bytes memory rrData = data.substring(offset, size);
if (deleteRecord) {
if (records[node][version][nameHash][resource].length != 0) {
nameEntriesCount[node][version][nameHash]--;
}
delete(records[node][version][nameHash][resource]);
emit DNSRecordDeleted(node, name, resource);
} else {
if (records[node][version][nameHash][resource].length == 0) {
nameEntriesCount[node][version][nameHash]++;
}
records[node][version][nameHash][resource] = rrData;
emit DNSRecordChanged(node, name, resource, rrData);
}
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
import "./AddrResolver.sol";
abstract contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 165 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP165 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 165 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 165 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) virtual override(AddrResolver, ResolverBase) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) virtual external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) virtual external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) virtual external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x The X coordinate of the curve point for the public key.
* @return y The Y coordinate of the curve point for the public key.
*/
function pubkey(bytes32 node) virtual external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
import "../ResolverBase.sol";
abstract contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexed indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) virtual external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) virtual external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) virtual override public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;pragma experimental ABIEncoderV2;
import "@ensdomains/ens/contracts/ENS.sol";
import "./profiles/ABIResolver.sol";
import "./profiles/AddrResolver.sol";
import "./profiles/ContentHashResolver.sol";
import "./profiles/DNSResolver.sol";
import "./profiles/InterfaceResolver.sol";
import "./profiles/NameResolver.sol";
import "./profiles/PubkeyResolver.sol";
import "./profiles/TextResolver.sol";
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal override view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
function multicall(bytes[] calldata data) external returns(bytes[] memory results) {
results = new bytes[](data.length);
for(uint i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
require(success);
results[i] = result;
}
return results;
}
function supportsInterface(bytes4 interfaceID) virtual override(ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver) public pure returns(bool) {
return super.supportsInterface(interfaceID);
}
}
pragma solidity ^0.7.4;
abstract contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) virtual public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal virtual view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
function bytesToAddress(bytes memory b) internal pure returns(address payable a) {
require(b.length == 20);
assembly {
a := div(mload(add(b, 32)), exp(256, 12))
}
}
function addressToBytes(address a) internal pure returns(bytes memory b) {
b = new bytes(20);
assembly {
mstore(add(b, 32), mul(a, exp(256, 12)))
}
}
}
pragma solidity ^0.7.4;
import "./BytesUtils.sol";
import "@ensdomains/buffer/contracts/Buffer.sol";
/**
* @dev RRUtils is a library that provides utilities for parsing DNS resource records.
*/
library RRUtils {
using BytesUtils for *;
using Buffer for *;
/**
* @dev Returns the number of bytes in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The length of the DNS name at 'offset', in bytes.
*/
function nameLength(bytes memory self, uint offset) internal pure returns(uint) {
uint idx = offset;
while (true) {
assert(idx < self.length);
uint labelLen = self.readUint8(idx);
idx += labelLen + 1;
if (labelLen == 0) {
break;
}
}
return idx - offset;
}
/**
* @dev Returns a DNS format name at the specified offset of self.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return ret The name.
*/
function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {
uint len = nameLength(self, offset);
return self.substring(offset, len);
}
/**
* @dev Returns the number of labels in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The number of labels in the DNS name at 'offset', in bytes.
*/
function labelCount(bytes memory self, uint offset) internal pure returns(uint) {
uint count = 0;
while (true) {
assert(offset < self.length);
uint labelLen = self.readUint8(offset);
offset += labelLen + 1;
if (labelLen == 0) {
break;
}
count += 1;
}
return count;
}
uint constant RRSIG_TYPE = 0;
uint constant RRSIG_ALGORITHM = 2;
uint constant RRSIG_LABELS = 3;
uint constant RRSIG_TTL = 4;
uint constant RRSIG_EXPIRATION = 8;
uint constant RRSIG_INCEPTION = 12;
uint constant RRSIG_KEY_TAG = 16;
uint constant RRSIG_SIGNER_NAME = 18;
struct SignedSet {
uint16 typeCovered;
uint8 algorithm;
uint8 labels;
uint32 ttl;
uint32 expiration;
uint32 inception;
uint16 keytag;
bytes signerName;
bytes data;
bytes name;
}
function readSignedSet(bytes memory data) internal pure returns(SignedSet memory self) {
self.typeCovered = data.readUint16(RRSIG_TYPE);
self.algorithm = data.readUint8(RRSIG_ALGORITHM);
self.labels = data.readUint8(RRSIG_LABELS);
self.ttl = data.readUint32(RRSIG_TTL);
self.expiration = data.readUint32(RRSIG_EXPIRATION);
self.inception = data.readUint32(RRSIG_INCEPTION);
self.keytag = data.readUint16(RRSIG_KEY_TAG);
self.signerName = readName(data, RRSIG_SIGNER_NAME);
self.data = data.substring(RRSIG_SIGNER_NAME + self.signerName.length, data.length - RRSIG_SIGNER_NAME - self.signerName.length);
}
function rrs(SignedSet memory rrset) internal pure returns(RRIterator memory) {
return iterateRRs(rrset.data, 0);
}
/**
* @dev An iterator over resource records.
*/
struct RRIterator {
bytes data;
uint offset;
uint16 dnstype;
uint16 class;
uint32 ttl;
uint rdataOffset;
uint nextOffset;
}
/**
* @dev Begins iterating over resource records.
* @param self The byte string to read from.
* @param offset The offset to start reading at.
* @return ret An iterator object.
*/
function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
/**
* @dev Returns true iff there are more RRs to iterate.
* @param iter The iterator to check.
* @return True iff the iterator has finished.
*/
function done(RRIterator memory iter) internal pure returns(bool) {
return iter.offset >= iter.data.length;
}
/**
* @dev Moves the iterator to the next resource record.
* @param iter The iterator to advance.
*/
function next(RRIterator memory iter) internal pure {
iter.offset = iter.nextOffset;
if (iter.offset >= iter.data.length) {
return;
}
// Skip the name
uint off = iter.offset + nameLength(iter.data, iter.offset);
// Read type, class, and ttl
iter.dnstype = iter.data.readUint16(off);
off += 2;
iter.class = iter.data.readUint16(off);
off += 2;
iter.ttl = iter.data.readUint32(off);
off += 4;
// Read the rdata
uint rdataLength = iter.data.readUint16(off);
off += 2;
iter.rdataOffset = off;
iter.nextOffset = off + rdataLength;
}
/**
* @dev Returns the name of the current record.
* @param iter The iterator.
* @return A new bytes object containing the owner name from the RR.
*/
function name(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));
}
/**
* @dev Returns the rdata portion of the current record.
* @param iter The iterator.
* @return A new bytes object containing the RR's RDATA.
*/
function rdata(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);
}
uint constant DNSKEY_FLAGS = 0;
uint constant DNSKEY_PROTOCOL = 2;
uint constant DNSKEY_ALGORITHM = 3;
uint constant DNSKEY_PUBKEY = 4;
struct DNSKEY {
uint16 flags;
uint8 protocol;
uint8 algorithm;
bytes publicKey;
}
function readDNSKEY(bytes memory data, uint offset, uint length) internal pure returns(DNSKEY memory self) {
self.flags = data.readUint16(offset + DNSKEY_FLAGS);
self.protocol = data.readUint8(offset + DNSKEY_PROTOCOL);
self.algorithm = data.readUint8(offset + DNSKEY_ALGORITHM);
self.publicKey = data.substring(offset + DNSKEY_PUBKEY, length - DNSKEY_PUBKEY);
}
uint constant DS_KEY_TAG = 0;
uint constant DS_ALGORITHM = 2;
uint constant DS_DIGEST_TYPE = 3;
uint constant DS_DIGEST = 4;
struct DS {
uint16 keytag;
uint8 algorithm;
uint8 digestType;
bytes digest;
}
function readDS(bytes memory data, uint offset, uint length) internal pure returns(DS memory self) {
self.keytag = data.readUint16(offset + DS_KEY_TAG);
self.algorithm = data.readUint8(offset + DS_ALGORITHM);
self.digestType = data.readUint8(offset + DS_DIGEST_TYPE);
self.digest = data.substring(offset + DS_DIGEST, length - DS_DIGEST);
}
struct NSEC3 {
uint8 hashAlgorithm;
uint8 flags;
uint16 iterations;
bytes salt;
bytes32 nextHashedOwnerName;
bytes typeBitmap;
}
uint constant NSEC3_HASH_ALGORITHM = 0;
uint constant NSEC3_FLAGS = 1;
uint constant NSEC3_ITERATIONS = 2;
uint constant NSEC3_SALT_LENGTH = 4;
uint constant NSEC3_SALT = 5;
function readNSEC3(bytes memory data, uint offset, uint length) internal pure returns(NSEC3 memory self) {
uint end = offset + length;
self.hashAlgorithm = data.readUint8(offset + NSEC3_HASH_ALGORITHM);
self.flags = data.readUint8(offset + NSEC3_FLAGS);
self.iterations = data.readUint16(offset + NSEC3_ITERATIONS);
uint8 saltLength = data.readUint8(offset + NSEC3_SALT_LENGTH);
offset = offset + NSEC3_SALT;
self.salt = data.substring(offset, saltLength);
offset += saltLength;
uint8 nextLength = data.readUint8(offset);
require(nextLength <= 32);
offset += 1;
self.nextHashedOwnerName = data.readBytesN(offset, nextLength);
offset += nextLength;
self.typeBitmap = data.substring(offset, end - offset);
}
function checkTypeBitmap(NSEC3 memory self, uint16 rrtype) internal pure returns(bool) {
return checkTypeBitmap(self.typeBitmap, 0, rrtype);
}
/**
* @dev Checks if a given RR type exists in a type bitmap.
* @param bitmap The byte string to read the type bitmap from.
* @param offset The offset to start reading at.
* @param rrtype The RR type to check for.
* @return True if the type is found in the bitmap, false otherwise.
*/
function checkTypeBitmap(bytes memory bitmap, uint offset, uint16 rrtype) internal pure returns (bool) {
uint8 typeWindow = uint8(rrtype >> 8);
uint8 windowByte = uint8((rrtype & 0xff) / 8);
uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));
for (uint off = offset; off < bitmap.length;) {
uint8 window = bitmap.readUint8(off);
uint8 len = bitmap.readUint8(off + 1);
if (typeWindow < window) {
// We've gone past our window; it's not here.
return false;
} else if (typeWindow == window) {
// Check this type bitmap
if (len <= windowByte) {
// Our type is past the end of the bitmap
return false;
}
return (bitmap.readUint8(off + windowByte + 2) & windowBitmask) != 0;
} else {
// Skip this type bitmap
off += len + 2;
}
}
return false;
}
function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {
if (self.equals(other)) {
return 0;
}
uint off;
uint otheroff;
uint prevoff;
uint otherprevoff;
uint counts = labelCount(self, 0);
uint othercounts = labelCount(other, 0);
// Keep removing labels from the front of the name until both names are equal length
while (counts > othercounts) {
prevoff = off;
off = progress(self, off);
counts--;
}
while (othercounts > counts) {
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
othercounts--;
}
// Compare the last nonequal labels to each other
while (counts > 0 && !self.equals(off, other, otheroff)) {
prevoff = off;
off = progress(self, off);
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
counts -= 1;
}
if (off == 0) {
return -1;
}
if(otheroff == 0) {
return 1;
}
return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));
}
function progress(bytes memory body, uint off) internal pure returns(uint) {
return off + 1 + body.readUint8(off);
}
}
pragma solidity ^0.7.4;
library BytesUtils {
/*
* @dev Returns the keccak-256 hash of a byte range.
* @param self The byte string to hash.
* @param offset The position to start hashing at.
* @param len The number of bytes to hash.
* @return The hash of the byte range.
*/
function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := keccak256(add(add(self, 32), offset), len)
}
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal.
* @param self The first bytes to compare.
* @param other The second bytes to compare.
* @return The result of the comparison.
*/
function compare(bytes memory self, bytes memory other) internal pure returns (int) {
return compare(self, 0, self.length, other, 0, other.length);
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two bytes are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first bytes to compare.
* @param offset The offset of self.
* @param len The length of self.
* @param other The second bytes to compare.
* @param otheroffset The offset of the other string.
* @param otherlen The length of the other string.
* @return The result of the comparison.
*/
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @param len The number of bytes to compare
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
/*
* @dev Returns true if the two byte ranges are equal with offsets.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
/*
* @dev Compares a range of 'self' to all of 'other' and returns True iff
* they are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, bytes memory other) internal pure returns(bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
/*
* @dev Returns the 8-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 8 bits of the string, interpreted as an integer.
*/
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {
return uint8(self[idx]);
}
/*
* @dev Returns the 16-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 16 bits of the string, interpreted as an integer.
*/
function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
/*
* @dev Returns the 32-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bits of the string, interpreted as an integer.
*/
function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
/*
* @dev Returns the n byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes.
* @param len The number of bytes.
* @return The specified 32 bytes of the string.
*/
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) {
require(len <= 32);
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Copies a substring into a new byte string.
* @param self The byte string to copy from.
* @param offset The offset to start copying at.
* @param len The number of bytes to copy.
*/
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint dest;
uint src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
// Maps characters from 0x30 to 0x7A to their base32 values.
// 0xFF represents invalid characters in that range.
bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F';
/**
* @dev Decodes unpadded base32 data of up to one word in length.
* @param self The data to decode.
* @param off Offset into the string to start at.
* @param len Number of characters to decode.
* @return The decoded data, left aligned.
*/
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
uint8 decoded;
for(uint i = 0; i < len; i++) {
bytes1 char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
}
pragma solidity >0.4.18;
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
|
Returns the ABI associated with an ENS node. Defined in EIP205. node The ENS node to query contentTypes A bitwise OR of the ABI formats accepted by the caller. return contentType The content type of the return value return data The ABI data/
|
function ABI(bytes32 node, uint256 contentTypes) virtual external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
| 388,391
|
pragma solidity 0.5.0;
import "openzeppelin-eth/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-eth/contracts/math/SafeMath.sol";
import "./compound/ICErc20.sol";
import "openzeppelin-eth/contracts/ownership/Ownable.sol";
import "kleros/contracts/data-structures/SortitionSumTreeFactory.sol";
import "./UniformRandomNumber.sol";
import "fixidity/contracts/FixidityLib.sol";
/**
* @title The Pool contract for PoolTogether
* @author Brendan Asselstine
* @notice This contract implements a "lossless pool". The pool exists in three states: open, locked, and complete.
* The pool begins in the open state during which users can buy any number of tickets. The more tickets they purchase, the greater their chances of winning.
* After the lockStartBlock the owner may lock the pool. The pool transfers the pool of ticket money into the Compound Finance money market and no more tickets are sold.
* After the lockEndBlock the owner may unlock the pool. The pool will withdraw the ticket money from the money market, plus earned interest, back into the contract. The fee will be sent to
* the owner, and users will be able to withdraw their ticket money and winnings, if any.
* @dev All monetary values are stored internally as fixed point 24.
*/
// WARNING: This contract will break if the amount of interest earned is negative (is that possible?).
contract Pool is Ownable {
using SafeMath for uint256;
/**
* Emitted when "tickets" have been purchased.
* @param sender The purchaser of the tickets
* @param count The number of tickets purchased
* @param totalPrice The total cost of the tickets
*/
event BoughtTickets(address indexed sender, int256 count, uint256 totalPrice);
/**
* Emitted when a user withdraws from the pool.
* @param sender The user that is withdrawing from the pool
* @param amount The amount that the user withdrew
*/
event Withdrawn(address indexed sender, int256 amount, int256 remainingTickets);
/**
* Emitted when the pool is complete. Total Winnings is unifixed.
*/
event DrawingComplete(int256 winningGroup, int256 totalWinnings);
struct Entry {
address addr;
// this may be unneeded and expensive but I'll optimize later
// it shows up twice: in the struct and as the key in users dict
string username;
int256 amount; // this is fixedPoint24
int256 ticketCount;
int256 totalWinnings; // this is fixedPoint24
int256 groupId;
// TODO: collectibles
}
struct PendingEntry {
address addr;
int256 amount; // fixedPoint24
int256 ticketCount;
}
struct Group {
address[] members;
// this are the members that are authorized to join the group
// every member has invite access
address[] allowedEntrants;
// ticketCount: computed from members in frontend
// amount: computed from members in frontend
}
bytes32 public constant SUM_TREE_KEY = "PoolPool";
bool public hasActivated = false;
// total principle
int256 private principleAmount; // fixed point 24
bytes32 private secretHash;
bytes32 private secret;
// total principle + interest
int256 private finalAmount; //fixed point 24
// winnings from previous draws that are unclaimed and therefore still in compound
int256 private unclaimedWinnings; // fixed point 24
// When new winnings are calculated in each drawing, the prize pool is calculated as
// finalAmount - unclaimedWinnings - principleAmount
// TODO: optimize
// We need to keep this... stored twice. Not pretty
// Needed to access the entry for msg.sender
mapping (address => Entry) private activeEntries;
// needed to invite by username
mapping (string => address) private users;
//mapping of groups
Group[] private groups;
mapping (address => PendingEntry) private pendingEntries;
// Needed to loops over pendingEntries in activateEntries
address[] pendingAddresses;
// TODO: decrement entryCount on full withdrawal
uint256 public entryCount;
ICErc20 public moneyMarket;
IERC20 public token;
int256 private ticketPrice; //fixed point 24
int256 private feeFraction; //fixed point 24
address private winningAddress;
int256 private winningGroup;
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees;
/**
* @notice Creates a new Pool.
* @param _moneyMarket The Compound money market to supply tokens to.
* @param _token The ERC20 token to be used.
* @param _ticketPrice The price of each ticket (fixed point 18)
* @param _feeFractionFixedPoint18 The fraction of the winnings going to the owner (fixed point 18)
* @param _secretHash the secret hash for the first drawing
*/
constructor (
ICErc20 _moneyMarket,
IERC20 _token,
int256 _ticketPrice,
int256 _feeFractionFixedPoint18,
bytes32 _secretHash
) public {
require(address(_moneyMarket) != address(0), "money market address cannot be zero");
require(address(_token) != address(0), "token address cannot be zero");
require(_ticketPrice > 0, "ticket price must be greater than zero");
require(_feeFractionFixedPoint18 >= 0, "fee must be zero or greater");
require(_feeFractionFixedPoint18 <= 1000000000000000000, "fee fraction must be less than 1");
feeFraction = FixidityLib.newFixed(_feeFractionFixedPoint18, uint8(18));
ticketPrice = FixidityLib.newFixed(_ticketPrice);
sortitionSumTrees.createTree(SUM_TREE_KEY, 4);
secretHash = _secretHash;
moneyMarket = _moneyMarket;
token = _token;
unclaimedWinnings = FixidityLib.newFixed(0);
}
modifier hasEntry {
require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first.");
_;
}
modifier hasGroup {
require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first.");
require(activeEntries[msg.sender].groupId >= 0, "The user has not created or joined a group yet.");
_;
}
modifier isSolo {
require(activeEntries[msg.sender].addr == msg.sender, "The user has not yet entered the game. Buy a ticket first.");
require(activeEntries[msg.sender].groupId == -1, "The user is already in a group. They should leave before joining another.");
_;
}
function getUnclaimedWinnings() external view returns (int256) {
return FixidityLib.fromFixed(unclaimedWinnings);
}
/**
* @notice deletes the element at a given index from the array
* @param index the index to delte
* @param array the array to modify
* @author jmartinmcfly (copied from https://ethereum.stackexchange.com/questions/1527/how-to-delete-an-element-at-a-certain-index-in-an-array/1528)
*/
function _burn(uint256 index, address[] storage array) internal {
require(index < array.length, "Bad Index");
array[index] = array[array.length-1];
delete array[array.length-1];
array.length--;
}
// getter for groups
function getGroupId(address _addr) public view returns (int256) {
return activeEntries[_addr].groupId;
}
function getGroup(uint256 groupId) public view returns (
address[] memory members,
address[] memory allowedEntrants
) {
Group storage theGroup = groups[groupId];
return (theGroup.members, theGroup.allowedEntrants);
}
event NewGroupMade(int idNewGroup, address groupCreatorAddr);
/**
* @notice Creates a new group and places msg.sender within it
*/
// WARNING: this may not work. I may need to make a mapping for groups
// and store the keys for that mapping in an array
function createGroup() external hasEntry {
int newGroupId = int(groups.length);
groups.length += 1;
Group storage newGroup = groups[uint(newGroupId)];
newGroup.members.push(msg.sender);
Entry storage senderEntry = activeEntries[msg.sender];
senderEntry.groupId = newGroupId;
emit NewGroupMade(senderEntry.groupId, msg.sender);
}
/**
* @notice Puts a user in a group if they've been invited and removes them from
* the allowed invite list.
* @param _groupId The group to join
* @author jmartinmcfly
*/
function joinGroup(int256 _groupId) external hasEntry isSolo {
// require the the user is in allowed
Group storage theGroup = groups[uint(_groupId)];
bool isAllowed = false;
for (uint i = 0; i < theGroup.allowedEntrants.length; i++) {
if (theGroup.allowedEntrants[i] == msg.sender) {
isAllowed = true;
// WARNING: This may get funky because storage
_burn(i, theGroup.allowedEntrants);
}
}
require(isAllowed, "You do not have permission to join this group.");
theGroup.members.push(msg.sender);
// change the entry to match the new group status
Entry storage newGroupMember = activeEntries[msg.sender];
newGroupMember.groupId = _groupId;
}
/**
* @notice Makes msg.sender leave their given group and become a solo player
* @author jmartinmcfly
*/
function leaveGroup() external hasEntry hasGroup {
Entry storage senderEntry = activeEntries[msg.sender];
// WARNING: This may get funky because storage
Group storage group = groups[uint(getGroupId(msg.sender))];
uint index = group.members.length;
for (uint i = 0; i < group.members.length; i++) {
if (group.members[i] == msg.sender) {
index = i;
}
}
require(index < group.members.length, "Something went wrong with the leave op!");
// remove the msg.sender from the list of members
_burn(index, group.members);
// set the groupId of the user to -1 aka "does not exist"
senderEntry.groupId = -1;
}
event UserInvited(int256 theGroup, address invitee, address invitor);
/**
* @notice Gives the passed user permission to join the group of msg.sender
* @param _username the username of the user to invite
* @author jmartinmcfly
*/
function invite(string calldata _username) external hasEntry hasGroup {
// require that the user "_username" exists
require(users[_username] != address(0), "User doesn't exist");
address inviteeAddress = users[_username];
int256 groupId = activeEntries[msg.sender].groupId;
Group storage invitingGroup = groups[uint(groupId)];
invitingGroup.allowedEntrants.push(inviteeAddress);
emit UserInvited(groupId ,inviteeAddress, msg.sender);
}
function setUsername(string calldata _username) external {
if (_hasEntry(msg.sender)) {
users[_username] = msg.sender;
Entry storage entryToModify = activeEntries[msg.sender];
entryToModify.username = _username;
} else {
activeEntries[msg.sender] = Entry(
msg.sender,
_username,
0,
0,
0,
-1
);
users[_username] = msg.sender;
}
}
event BalanceEvent(uint256 depositedBalance);
/**
* @notice Buys a pool ticket. Only possible while the Pool is in the "open" state. The
* user can buy any number of tickets. Each ticket is a chance at winning.
* @param _countNonFixed The number of tickets the user wishes to buy.
*/
function buyTickets (int256 _countNonFixed) public {
require(_countNonFixed > 0, "number of tickets is less than or equal to zero");
int256 count = FixidityLib.newFixed(_countNonFixed);
int256 totalDeposit = FixidityLib.multiply(ticketPrice, count);
uint256 totalDepositNonFixed = uint256(FixidityLib.fromFixed(totalDeposit));
require(token.transferFrom(msg.sender, address(this), totalDepositNonFixed), "token transfer failed");
// send the newly sent tokens to the moneymarket
require(token.approve(address(moneyMarket), totalDepositNonFixed), "could not approve money market spend");
emit BalanceEvent(totalDepositNonFixed);
// TODO: DOES THIS WORK? Can you mint twice?
require(moneyMarket.mint(totalDepositNonFixed) == 0, "could not supply money market");
if (_hasEntry(msg.sender)) {
if (!_hasPendingEntry(msg.sender)) {
pendingAddresses.push(msg.sender);
pendingEntries[msg.sender] = PendingEntry(msg.sender, totalDeposit, _countNonFixed);
} else {
pendingEntries[msg.sender].amount = FixidityLib.add(pendingEntries[msg.sender].amount, totalDeposit);
pendingEntries[msg.sender].ticketCount = pendingEntries[msg.sender].ticketCount + _countNonFixed;
}
} else {
activeEntries[msg.sender] = Entry(
msg.sender,
"",
FixidityLib.newFixed(0),
0,
FixidityLib.newFixed(0),
-1
);
pendingEntries[msg.sender] = PendingEntry(msg.sender, totalDeposit, _countNonFixed);
entryCount = entryCount.add(1);
}
principleAmount = FixidityLib.add(principleAmount, totalDeposit);
// the total amount cannot exceed the max pool size
require(principleAmount <= maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv()), "pool size exceeds maximum");
emit BoughtTickets(msg.sender, _countNonFixed, totalDepositNonFixed);
}
/**
* @notice Selects a winning address (and therefore group) and
* updates winnings of winning group members.
* @param _secret the secret for this drawing
* @param _newSecretHash the hash of the secret for the next drawing
* Fires the PoolUnlocked event.
*/
function draw(bytes32 _secret, bytes32 _newSecretHash) public onlyOwner {
require(hasActivated, "the pool has not been activated yet");
require(keccak256(abi.encodePacked(_secret)) == secretHash, "secret does not match");
// we store the secret in the contract for ease of passing around and so
// users can (with some annoyance) recreate a drawing themselves
secret = _secret;
winningAddress = calculateWinner();
winningGroup = activeEntries[winningAddress].groupId;
require(_newSecretHash != 0, "secret hash must be defined");
// set new secret hash for next drawing
secretHash = _newSecretHash;
int256 totalWinningsFixed = updatePayouts(winningAddress);
// pay the owner their fee
uint256 fee = feeAmount();
if (fee > 0) {
require(token.transfer(owner(), fee), "could not transfer winnings");
}
// shift entries from pendingEntries to activeEntries
activateEntriesInternal();
emit DrawingComplete(winningGroup, FixidityLib.fromFixed(totalWinningsFixed));
}
/**
* @notice Shifts all inactive entries to active entries and updates sortition tree/
* This will normally only be called by draw. However, before the first ever drawing
* in the history of the contract, this will be called manually by the pool operator.
* @author jmartinmcfly
*/
// TODO: address potential gas limit issues here
function activateEntries() public onlyOwner {
require(!hasActivated, "You have already activated the pool");
hasActivated = true;
// update Entries
for (uint i = 0; i < pendingAddresses.length; i++) {
PendingEntry storage current = pendingEntries[pendingAddresses[i]];
Entry storage currentActive = activeEntries[current.addr];
currentActive.amount = FixidityLib.add(current.amount, currentActive.amount);
currentActive.ticketCount = currentActive.ticketCount + current.ticketCount;
//clear the pendingEntry
current.amount = FixidityLib.newFixed(0);
current.ticketCount = 0;
// update sortition tree entry
sortitionSumTrees.set(SUM_TREE_KEY, uint256(FixidityLib.fromFixed(currentActive.amount)), bytes32(uint256(current.addr)));
}
delete pendingAddresses;
}
/**
* @notice Shifts all inactive entries to active entries and updates sortition tree/
* This will normally only be called by draw. However, before the first ever drawing
* in the history of the contract, this will be called manually by the pool operator.
* @author jmartinmcfly
*/
// TODO: address potential gas limit issues here
function activateEntriesInternal() internal onlyOwner {
// update Entries
for (uint i = 0; i < pendingAddresses.length; i++) {
PendingEntry storage current = pendingEntries[pendingAddresses[i]];
Entry storage currentActive = activeEntries[current.addr];
currentActive.amount = FixidityLib.add(current.amount, currentActive.amount);
currentActive.ticketCount = currentActive.ticketCount + current.ticketCount;
//clear the pendingEntry
current.amount = FixidityLib.newFixed(0);
current.ticketCount = 0;
// update sortition tree entry
sortitionSumTrees.set(SUM_TREE_KEY, uint256(FixidityLib.fromFixed(currentActive.amount)), bytes32(uint256(current.addr)));
}
delete pendingAddresses;
}
event NetTotalWinnings(int theWinnings, address theWinner);
/**
* @notice Updates the payouts of all activeEntries in the winning group (entry.totalWinnings).
* Also updates unclaimedWinnings to reflect the new set of winners,
* Effectively resetting the prize pool.
* @param _winningAddress The address of the winning entry
* @author jmartinmcfly
*/
function updatePayouts(address _winningAddress) internal returns (int256) {
int totalWinningsFixed;
// determine group of address
Entry storage winner = activeEntries[_winningAddress];
// TODO: hacky, change group structure later
finalAmount = FixidityLib.newFixed(int(moneyMarket.balanceOfUnderlying(address(this))));
int256 totalMinusUnclaimedPrizes = FixidityLib.subtract(finalAmount, unclaimedWinnings);
if (winner.groupId == -1) {
// winner gets the whole shebang
totalWinningsFixed = netWinningsFixedPoint24();
emit NetTotalWinnings(FixidityLib.fromFixed(totalWinningsFixed), _winningAddress);
// reset prize pool
unclaimedWinnings = FixidityLib.add(unclaimedWinnings, totalWinningsFixed);
winner.totalWinnings = FixidityLib.add(winner.totalWinnings, totalWinningsFixed);
} else {
Group storage winningGroupFull = groups[uint(winner.groupId)];
// calc total tickets
int totalTickets = 0;
for (uint i = 0; i < winningGroupFull.members.length; i++) {
totalTickets = totalTickets + activeEntries[winningGroupFull.members[i]].ticketCount;
}
// get the total winnings from the drawing (minus the fee)
totalWinningsFixed = netWinningsFixedPoint24();
emit NetTotalWinnings(FixidityLib.fromFixed(totalWinningsFixed),_winningAddress);
// reset prize pool
unclaimedWinnings = FixidityLib.add(unclaimedWinnings, totalWinningsFixed);
// update payouts of all activeEntries in the group
for (uint i = 0; i < winningGroupFull.members.length; i++) {
Entry storage entryToChange = activeEntries[winningGroupFull.members[i]];
int proportion = FixidityLib.newFixedFraction(entryToChange.ticketCount, totalTickets);
int winningsCut = FixidityLib.multiply(proportion, totalWinningsFixed);
entryToChange.totalWinnings = FixidityLib.add(entryToChange.totalWinnings, winningsCut);
}
}
return totalWinningsFixed;
}
/**
* @notice donate to prize pool
* @param _amount amount to donate
*/
function donateToPrizePool(uint _amount) external {
require(_amount > 0, "amount of donation is less than or equal to zero");
uint256 _countNonFixed = _amount;
require(token.transferFrom(msg.sender, address(this), _countNonFixed), "token transfer failed");
// send the newly sent tokens to the moneymarket
emit BalanceEvent(_countNonFixed);
require(token.approve(address(moneyMarket), _countNonFixed), "could not approve money market spend");
emit BalanceEvent(_countNonFixed);
// TODO: DOES THIS WORK? Can you mint twice?
require(moneyMarket.mint(_countNonFixed) == 0, "could not supply money market");
}
/**
* @notice Transfers a users deposit, and potential winnings, back to them.
* The Pool must be unlocked.
* The user must have deposited funds. Fires the Withdrawn event.
*/
function withdraw(int _numTickets) public hasEntry {
require(_hasEntry(msg.sender), "entrant exists");
Entry storage entry = activeEntries[msg.sender];
PendingEntry storage pendingEntry = pendingEntries[msg.sender];
require(_numTickets <= (entry.ticketCount + pendingEntry.ticketCount), "You don't have that many tickets to withdraw!");
int256 prizeToWithdraw = FixidityLib.newFixed(0);
// if user has winnings add winnings to the withdrawal and clear their
// winnings + decrease unclaimed winnings
if (FixidityLib.fromFixed(entry.totalWinnings) != 0) {
prizeToWithdraw = FixidityLib.add(prizeToWithdraw, entry.totalWinnings);
// we have now withdrawn all winnings
entry.totalWinnings = FixidityLib.newFixed(0);
unclaimedWinnings = FixidityLib.subtract(unclaimedWinnings, prizeToWithdraw);
}
// then withdraw tickets
int256 numTicketsFixed = FixidityLib.newFixed(_numTickets);
int256 principleToWithdraw = FixidityLib.multiply(numTicketsFixed, ticketPrice);
if (pendingEntry.ticketCount > 0) {
if (_numTickets <= pendingEntry.ticketCount) {
pendingEntry.amount = FixidityLib.subtract(pendingEntry.amount, principleToWithdraw);
pendingEntry.ticketCount = pendingEntry.ticketCount - _numTickets;
} else {
int256 amountLeft = FixidityLib.subtract(principleToWithdraw, pendingEntry.amount);
int256 ticketsLeft = _numTickets - pendingEntry.ticketCount;
pendingEntry.amount = FixidityLib.newFixed(0);
pendingEntry.ticketCount = 0;
// update entry
entry.amount = FixidityLib.subtract(entry.amount, amountLeft);
entry.ticketCount = entry.ticketCount - ticketsLeft;
// update sum tree to reflect withdrawn principle
sortitionSumTrees.set(SUM_TREE_KEY, uint256(entry.amount), bytes32(uint256(msg.sender)));
}
} else {
entry.amount = FixidityLib.subtract(entry.amount, principleToWithdraw);
entry.ticketCount = entry.ticketCount - _numTickets;
// update sum tree to reflect withdrawn principle
sortitionSumTrees.set(SUM_TREE_KEY, uint256(entry.amount), bytes32(uint256(msg.sender)));
}
// calculate total withdrawal amount
int256 totalToWithdraw = FixidityLib.add(prizeToWithdraw, principleToWithdraw);
int256 totalToWithdrawNonFixed = FixidityLib.fromFixed(totalToWithdraw);
int256 remainingTickets = entry.ticketCount;
emit Withdrawn(msg.sender, totalToWithdrawNonFixed, remainingTickets);
// withdraw given amount from compound contract
require(moneyMarket.redeemUnderlying(uint256(totalToWithdrawNonFixed)) == 0, "could not redeem from compound");
require(token.transfer(msg.sender, uint256(totalToWithdrawNonFixed)), "could not transfer winnings");
}
function calculateWinner() private view returns (address) {
if (principleAmount > 0) {
return address(uint256(sortitionSumTrees.draw(SUM_TREE_KEY, randomToken())));
} else {
return address(0);
}
}
/**
* @notice Selects and returns the winner's address
* @return The winner's address
*/
function winnerAddress() public view returns (address) {
return winningAddress;
}
/**
* @notice Computes the total winnings for the drawing (interest - fee)
* @return the total winnings as a fixed point 24
*/
function netWinningsFixedPoint24() internal view returns (int256) {
return FixidityLib.subtract(grossWinningsFixedPoint24(), feeAmountFixedPoint24());
}
/**
* @notice Computes the total interest earned on the pool as a fixed point 24.
* This is what the winner will earn once the pool is unlocked.
* @return The total interest earned on the pool as a fixed point 24.
*/
function grossWinningsFixedPoint24() internal view returns (int256) {
int256 totalMinusUnclaimedPrizes = FixidityLib.subtract(finalAmount, unclaimedWinnings);
return FixidityLib.subtract(totalMinusUnclaimedPrizes, principleAmount);
}
/**
* @notice Calculates the size of the fee based on the gross winnings
* @return The fee for the pool to be transferred to the owner
*/
function feeAmount() public view returns (uint256) {
return uint256(FixidityLib.fromFixed(feeAmountFixedPoint24()));
}
/**
* @notice Calculates the fee for the pool by multiplying the gross winnings by the fee fraction.
* @return The fee for the pool as a fixed point 24
*/
function feeAmountFixedPoint24() internal view returns (int256) {
return FixidityLib.multiply(grossWinningsFixedPoint24(), feeFraction);
}
/**
* @notice Selects a random number in the range from [0, total tokens deposited)
* @return If the current block is before the end it returns 0, otherwise it returns the random number.
*/
function randomToken() public view returns (uint256) {
return _selectRandom(uint256(FixidityLib.fromFixed(principleAmount)));
}
/**
* @notice Selects a random number in the range [0, total)
* @param total The upper bound for the random number
* @return The random number
*/
function _selectRandom(uint256 total) internal view returns (uint256) {
return UniformRandomNumber.uniform(_entropy(), total);
}
/**
* @notice Computes the entropy used to generate the random number.
* The blockhash of the lock end block is XOR'd with the secret revealed by the owner.
* @return The computed entropy value
*/
function _entropy() internal view returns (uint256) {
return uint256(blockhash(block.number - 1) ^ secret);
}
/**
* @notice Retrieves information about the pool.
* @return A tuple containing:
* entryTotal (the total of all deposits)
* startBlock (the block after which the pool can be locked)
* endBlock (the block after which the pool can be unlocked)
* poolState (either OPEN, LOCKED, COMPLETE)
* winner (the address of the winner)
* supplyBalanceTotal (the total deposits plus any interest from Compound)
* ticketCost (the cost of each ticket in DAI)
* participantCount (the number of unique purchasers of tickets)
* maxPoolSize (the maximum theoretical size of the pool to prevent overflow)
* estimatedInterestFixedPoint18 (the estimated total interest percent for this pool)
* hashOfSecret (the hash of the secret the owner submitted upon locking)
*/
function getInfo() public view returns (
int256 entryTotal,
address winner,
int256 supplyBalanceTotal,
int256 ticketCost,
uint256 participantCount,
int256 maxPoolSize,
int256 estimatedInterestFixedPoint18,
bytes32 hashOfSecret
) {
return (
FixidityLib.fromFixed(principleAmount),
winningAddress,
FixidityLib.fromFixed(finalAmount),
FixidityLib.fromFixed(ticketPrice),
entryCount,
FixidityLib.fromFixed(maxPoolSizeFixedPoint24(FixidityLib.maxFixedDiv())),
FixidityLib.fromFixed(currentInterestFractionFixedPoint24(), uint8(18)),
secretHash
);
}
event Tester(string toTest);
// TODO: test
function userInfo(address _addr) external returns (
address addrReturned,
string memory usernameReturned,
int256 totalAmountReturned,
int256 totalTicketsReturned,
int256 activeAmountReturned,
int256 activeTicketsReturned,
int256 pendingAmountReturned,
int256 pendingTicketsReturned,
int256 totalWinningsReturned,
int256 groupIdReturned
) {
Entry storage entry = activeEntries[_addr];
PendingEntry storage pendingEntry = pendingEntries[_addr];
int256 totalAmount = FixidityLib.fromFixed(FixidityLib.add(pendingEntry.amount, entry.amount));
emit Tester(entry.username);
return (
entry.addr,
entry.username,
totalAmount,
entry.ticketCount + pendingEntry.ticketCount,
FixidityLib.fromFixed(entry.amount),
entry.ticketCount,
FixidityLib.fromFixed(pendingEntry.amount),
pendingEntry.ticketCount,
FixidityLib.fromFixed(entry.totalWinnings),
entry.groupId
);
}
/**
* @notice Retrieves information about a user's entry in the Pool.
* @return Returns a tuple containing:
* addr (the address of the user)
* username
* amount (the amount they deposited)
* ticketCount (the number of tickets they have bought)
* totalWinnings (total unwithdrawn winnings of the user. Doesn't count principle)
* groupId (the id of the user's group)
*/
function getEntry(address _addr) public view returns (
address addr,
string memory username,
int256 amount,
int256 ticketCount,
int256 totalWinnings,
int256 groupId
) {
Entry storage entry = activeEntries[_addr];
//emit TotalWinnings(entry.totalWinnings);
//emit TotalWinnings(FixidityLib.fromFixed(entry.totalWinnings));
return (
entry.addr,
entry.username,
FixidityLib.fromFixed(entry.amount),
entry.ticketCount,
FixidityLib.fromFixed(entry.totalWinnings),
entry.groupId
);
}
/**
* @notice Retrieves information about a user's entry in the Pool.
* @return Returns a tuple containing:
* addr (the address of the user)
* username
* amount (the amount they deposited)
* ticketCount (the number of tickets they have bought)
* totalWinnings (total unwithdrawn winnings of the user. Doesn't count principle)
* groupId (the id of the user's group)
*/
function getEntryByUsername(string calldata theUsername) external view returns (
address addr,
string memory username,
int256 amount,
int256 ticketCount,
int256 totalWinnings,
int256 groupId
) {
Entry storage entry = activeEntries[users[theUsername]];
return (
entry.addr,
entry.username,
FixidityLib.fromFixed(entry.amount),
entry.ticketCount,
FixidityLib.fromFixed(entry.totalWinnings),
entry.groupId
);
}
/**
* @notice Retrieves information about a user's pending entry in the Pool.
* @return Returns a tuple containing:
* addr (the address of the user)
* amount (the amount they deposited)
* ticketCount (the number of tickets they have bought)
*/
function getPendingEntry(address _addr) public view returns (
address addr,
int256 amount,
int256 ticketCount
) {
PendingEntry storage pending = pendingEntries[_addr];
return (
pending.addr,
FixidityLib.fromFixed(pending.amount),
pending.ticketCount
);
}
/**
* @notice Calculates the maximum pool size so that it doesn't overflow after earning interest
* @dev poolSize = totalDeposits + totalDeposits * interest => totalDeposits = poolSize / (1 + interest)
* @return The maximum size of the pool to be deposited into the money market
*/
function maxPoolSizeFixedPoint24(int256 _maxValueFixedPoint24) public view returns (int256) {
/// Double the interest rate in case it increases over the lock period. Somewhat arbitrarily.
int256 interestFraction = FixidityLib.multiply(currentInterestFractionFixedPoint24(), FixidityLib.newFixed(2));
return FixidityLib.divide(_maxValueFixedPoint24, FixidityLib.add(interestFraction, FixidityLib.newFixed(1)));
}
/**
* @notice Estimates the current effective interest rate using the money market's current supplyRateMantissa and the lock duration in blocks.
* @return The current estimated effective interest rate
*/
// TODO: Add intelligent / enforced blockDuration
function currentInterestFractionFixedPoint24() public view returns (int256) {
// Chose a duration of one week
// arbitrary and not enforced by the contract at all
int256 blocksPerDay = 5760;
int256 daysPerDrawing = 7;
int256 blockDuration = blocksPerDay * daysPerDrawing;
// TODO: CHANGE THIS
blockDuration = 10;
int256 supplyRateMantissaFixedPoint24 = FixidityLib.newFixed(int256(supplyRateMantissa()), uint8(18));
return FixidityLib.multiply(supplyRateMantissaFixedPoint24, FixidityLib.newFixed(blockDuration));
}
/**
* @notice Extracts the supplyRateMantissa value from the money market contract
* @return The money market supply rate per block
*/
function supplyRateMantissa() public view returns (uint256) {
return moneyMarket.supplyRatePerBlock();
}
/**
* @notice Determines whether a given address has bought tickets
* @param _addr The given address
* @return Returns true if the given address bought tickets, false otherwise.
*/
function _hasEntry(address _addr) internal view returns (bool) {
return activeEntries[_addr].addr == _addr;
}
/**
* @notice Determines whether a given address has bought tickets
* @param _addr The given address
* @return Returns true if the given address bought tickets, false otherwise.
*/
function _hasPendingEntry(address _addr) internal returns (bool) {
return pendingEntries[_addr].addr == _addr;
}
}
|
donate to prize pool _amount amount to donate/ send the newly sent tokens to the moneymarket TODO: DOES THIS WORK? Can you mint twice?
|
function donateToPrizePool(uint _amount) external {
require(_amount > 0, "amount of donation is less than or equal to zero");
uint256 _countNonFixed = _amount;
require(token.transferFrom(msg.sender, address(this), _countNonFixed), "token transfer failed");
emit BalanceEvent(_countNonFixed);
require(token.approve(address(moneyMarket), _countNonFixed), "could not approve money market spend");
emit BalanceEvent(_countNonFixed);
require(moneyMarket.mint(_countNonFixed) == 0, "could not supply money market");
}
| 15,884,404
|
//Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
//Contract name: Grove
//Balance: 0 Ether
//Verification Date: 5/23/2017
//Transacion Count: 4
// CODE STARTS HERE
// Grove v0.2
/// @title GroveLib - Library for queriable indexed ordered data.
/// @author PiperMerriam - <pipermerriam@gmail.com>
library GroveLib {
/*
* Indexes for ordered data
*
* Address: 0xd07ce4329b27eb8896c51458468d98a0e4c0394c
*/
struct Index {
bytes32 id;
bytes32 name;
bytes32 root;
mapping (bytes32 => Node) nodes;
}
struct Node {
bytes32 nodeId;
bytes32 indexId;
bytes32 id;
int value;
bytes32 parent;
bytes32 left;
bytes32 right;
uint height;
}
/// @dev This is merely a shortcut for `sha3(owner, indexName)`
/// @param owner The address of the owner of this index.
/// @param indexName The human readable name for this index.
function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
return sha3(owner, indexName);
}
/// @dev This is merely a shortcut for `sha3(indexId, id)`
/// @param indexId The id for the index the node belongs to.
/// @param id The unique identifier for the data this node represents.
function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
return sha3(indexId, id);
}
function max(uint a, uint b) internal returns (uint) {
if (a >= b) {
return a;
}
return b;
}
/*
* Node getters
*/
/// @dev Retrieve the unique identifier for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeId(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].id;
}
/// @dev Retrieve the index id for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeIndexId(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].indexId;
}
/// @dev Retrieve the value for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeValue(Index storage index, bytes32 nodeId) constant returns (int) {
return index.nodes[nodeId].value;
}
/// @dev Retrieve the height of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeHeight(Index storage index, bytes32 nodeId) constant returns (uint) {
return index.nodes[nodeId].height;
}
/// @dev Retrieve the parent id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeParent(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].parent;
}
/// @dev Retrieve the left child id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeLeftChild(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].left;
}
/// @dev Retrieve the right child id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeRightChild(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].right;
}
/// @dev Retrieve the node id of the next node in the tree.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 nodeId) constant returns (bytes32) {
Node storage currentNode = index.nodes[nodeId];
if (currentNode.nodeId == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
// Trace left to latest child in left tree.
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.nodeId;
}
if (currentNode.parent != 0x0) {
// Now we trace back up through parent relationships, looking
// for a link where the child is the right child of it's
// parent.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.nodeId) {
return parent.nodeId;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
// This is the first node, and has no previous node.
return 0x0;
}
/// @dev Retrieve the node id of the previous node in the tree.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 nodeId) constant returns (bytes32) {
Node storage currentNode = index.nodes[nodeId];
if (currentNode.nodeId == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.right != 0x0) {
// Trace right to earliest child in right tree.
child = index.nodes[currentNode.right];
while (child.left != 0) {
child = index.nodes[child.left];
}
return child.nodeId;
}
if (currentNode.parent != 0x0) {
// if the node is the left child of it's parent, then the
// parent is the next one.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.left == child.nodeId) {
return parent.nodeId;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
// Now we need to trace all the way up checking to see if any parent is the
}
// This is the final node.
return 0x0;
}
/// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided.
/// @param index The index that the node is part of.
/// @param id The unique identifier of the data element the index node will represent.
/// @param value The value of the data element that represents it's total ordering with respect to other elementes.
function insert(Index storage index, bytes32 id, int value) public {
bytes32 nodeId = computeNodeId(index.id, id);
if (index.nodes[nodeId].nodeId == nodeId) {
// A node with this id already exists. If the value is
// the same, then just return early, otherwise, remove it
// and reinsert it.
if (index.nodes[nodeId].value == value) {
return;
}
remove(index, id);
}
uint leftHeight;
uint rightHeight;
bytes32 previousNodeId = 0x0;
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
rootNodeId = nodeId;
index.root = nodeId;
}
Node storage currentNode = index.nodes[rootNodeId];
// Do insertion
while (true) {
if (currentNode.indexId == 0x0) {
// This is a new unpopulated node.
currentNode.nodeId = nodeId;
currentNode.parent = previousNodeId;
currentNode.indexId = index.id;
currentNode.id = id;
currentNode.value = value;
break;
}
// Set the previous node id.
previousNodeId = currentNode.nodeId;
// The new node belongs in the right subtree
if (value >= currentNode.value) {
if (currentNode.right == 0x0) {
currentNode.right = nodeId;
}
currentNode = index.nodes[currentNode.right];
continue;
}
// The new node belongs in the left subtree.
if (currentNode.left == 0x0) {
currentNode.left = nodeId;
}
currentNode = index.nodes[currentNode.left];
}
// Rebalance the tree
_rebalanceTree(index, currentNode.nodeId);
}
/// @dev Checks whether a node for the given unique identifier exists within the given index.
/// @param index The index that should be searched
/// @param id The unique identifier of the data element to check for.
function exists(Index storage index, bytes32 id) constant returns (bool) {
bytes32 nodeId = computeNodeId(index.id, id);
return (index.nodes[nodeId].nodeId == nodeId);
}
/// @dev Remove the node for the given unique identifier from the index.
/// @param index The index that should be removed
/// @param id The unique identifier of the data element to remove.
function remove(Index storage index, bytes32 id) public {
bytes32 nodeId = computeNodeId(index.id, id);
Node storage replacementNode;
Node storage parent;
Node storage child;
bytes32 rebalanceOrigin;
Node storage nodeToDelete = index.nodes[nodeId];
if (nodeToDelete.id != id) {
// The id does not exist in the tree.
return;
}
if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) {
// This node is not a leaf node and thus must replace itself in
// it's tree by either the previous or next node.
if (nodeToDelete.left != 0x0) {
// This node is guaranteed to not have a right child.
replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.nodeId)];
}
else {
// This node is guaranteed to not have a left child.
replacementNode = index.nodes[getNextNode(index, nodeToDelete.nodeId)];
}
// The replacementNode is guaranteed to have a parent.
parent = index.nodes[replacementNode.parent];
// Keep note of the location that our tree rebalancing should
// start at.
rebalanceOrigin = replacementNode.nodeId;
// Join the parent of the replacement node with any subtree of
// the replacement node. We can guarantee that the replacement
// node has at most one subtree because of how getNextNode and
// getPreviousNode are used.
if (parent.left == replacementNode.nodeId) {
parent.left = replacementNode.right;
if (replacementNode.right != 0x0) {
child = index.nodes[replacementNode.right];
child.parent = parent.nodeId;
}
}
if (parent.right == replacementNode.nodeId) {
parent.right = replacementNode.left;
if (replacementNode.left != 0x0) {
child = index.nodes[replacementNode.left];
child.parent = parent.nodeId;
}
}
// Now we replace the nodeToDelete with the replacementNode.
// This includes parent/child relationships for all of the
// parent, the left child, and the right child.
replacementNode.parent = nodeToDelete.parent;
if (nodeToDelete.parent != 0x0) {
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.nodeId) {
parent.left = replacementNode.nodeId;
}
if (parent.right == nodeToDelete.nodeId) {
parent.right = replacementNode.nodeId;
}
}
else {
// If the node we are deleting is the root node so update
// the indexId to root node mapping.
index.root = replacementNode.nodeId;
}
replacementNode.left = nodeToDelete.left;
if (nodeToDelete.left != 0x0) {
child = index.nodes[nodeToDelete.left];
child.parent = replacementNode.nodeId;
}
replacementNode.right = nodeToDelete.right;
if (nodeToDelete.right != 0x0) {
child = index.nodes[nodeToDelete.right];
child.parent = replacementNode.nodeId;
}
}
else if (nodeToDelete.parent != 0x0) {
// The node being deleted is a leaf node so we only erase it's
// parent linkage.
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.nodeId) {
parent.left = 0x0;
}
if (parent.right == nodeToDelete.nodeId) {
parent.right = 0x0;
}
// keep note of where the rebalancing should begin.
rebalanceOrigin = parent.nodeId;
}
else {
// This is both a leaf node and the root node, so we need to
// unset the root node pointer.
index.root = 0x0;
}
// Now we zero out all of the fields on the nodeToDelete.
nodeToDelete.id = 0x0;
nodeToDelete.nodeId = 0x0;
nodeToDelete.indexId = 0x0;
nodeToDelete.value = 0;
nodeToDelete.parent = 0x0;
nodeToDelete.left = 0x0;
nodeToDelete.right = 0x0;
// Walk back up the tree rebalancing
if (rebalanceOrigin != 0x0) {
_rebalanceTree(index, rebalanceOrigin);
}
}
bytes2 constant GT = ">";
bytes2 constant LT = "<";
bytes2 constant GTE = ">=";
bytes2 constant LTE = "<=";
bytes2 constant EQ = "==";
function _compare(int left, bytes2 operator, int right) internal returns (bool) {
if (operator == GT) {
return (left > right);
}
if (operator == LT) {
return (left < right);
}
if (operator == GTE) {
return (left >= right);
}
if (operator == LTE) {
return (left <= right);
}
if (operator == EQ) {
return (left == right);
}
// Invalid operator.
throw;
}
function _getMaximum(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage currentNode = index.nodes[nodeId];
while (true) {
if (currentNode.right == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.right];
}
}
function _getMinimum(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage currentNode = index.nodes[nodeId];
while (true) {
if (currentNode.left == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.left];
}
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param index The index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(Index storage index, bytes2 operator, int value) public returns (bytes32) {
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
// Empty tree.
return 0x0;
}
Node storage currentNode = index.nodes[rootNodeId];
while (true) {
if (_compare(currentNode.value, operator, value)) {
// We have found a match but it might not be the
// *correct* match.
if ((operator == LT) || (operator == LTE)) {
// Need to keep traversing right until this is no
// longer true.
if (currentNode.right == 0x0) {
return currentNode.nodeId;
}
if (_compare(_getMinimum(index, currentNode.right), operator, value)) {
// There are still nodes to the right that
// match.
currentNode = index.nodes[currentNode.right];
continue;
}
return currentNode.nodeId;
}
if ((operator == GT) || (operator == GTE) || (operator == EQ)) {
// Need to keep traversing left until this is no
// longer true.
if (currentNode.left == 0x0) {
return currentNode.nodeId;
}
if (_compare(_getMaximum(index, currentNode.left), operator, value)) {
currentNode = index.nodes[currentNode.left];
continue;
}
return currentNode.nodeId;
}
}
if ((operator == LT) || (operator == LTE)) {
if (currentNode.left == 0x0) {
// There are no nodes that are less than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
if ((operator == GT) || (operator == GTE)) {
if (currentNode.right == 0x0) {
// There are no nodes that are greater than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (operator == EQ) {
if (currentNode.value < value) {
if (currentNode.right == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (currentNode.value > value) {
if (currentNode.left == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
}
}
}
function _rebalanceTree(Index storage index, bytes32 nodeId) internal {
// Trace back up rebalancing the tree and updating heights as
// needed..
Node storage currentNode = index.nodes[nodeId];
while (true) {
int balanceFactor = _getBalanceFactor(index, currentNode.nodeId);
if (balanceFactor == 2) {
// Right rotation (tree is heavy on the left)
if (_getBalanceFactor(index, currentNode.left) == -1) {
// The subtree is leaning right so it need to be
// rotated left before the current node is rotated
// right.
_rotateLeft(index, currentNode.left);
}
_rotateRight(index, currentNode.nodeId);
}
if (balanceFactor == -2) {
// Left rotation (tree is heavy on the right)
if (_getBalanceFactor(index, currentNode.right) == 1) {
// The subtree is leaning left so it need to be
// rotated right before the current node is rotated
// left.
_rotateRight(index, currentNode.right);
}
_rotateLeft(index, currentNode.nodeId);
}
if ((-1 <= balanceFactor) && (balanceFactor <= 1)) {
_updateNodeHeight(index, currentNode.nodeId);
}
if (currentNode.parent == 0x0) {
// Reached the root which may be new due to tree
// rotation, so set it as the root and then break.
break;
}
currentNode = index.nodes[currentNode.parent];
}
}
function _getBalanceFactor(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage node = index.nodes[nodeId];
return int(index.nodes[node.left].height) - int(index.nodes[node.right].height);
}
function _updateNodeHeight(Index storage index, bytes32 nodeId) internal {
Node storage node = index.nodes[nodeId];
node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1;
}
function _rotateLeft(Index storage index, bytes32 nodeId) internal {
Node storage originalRoot = index.nodes[nodeId];
if (originalRoot.right == 0x0) {
// Cannot rotate left if there is no right originalRoot to rotate into
// place.
throw;
}
// The right child is the new root, so it gets the original
// `originalRoot.parent` as it's parent.
Node storage newRoot = index.nodes[originalRoot.right];
newRoot.parent = originalRoot.parent;
// The original root needs to have it's right child nulled out.
originalRoot.right = 0x0;
if (originalRoot.parent != 0x0) {
// If there is a parent node, it needs to now point downward at
// the newRoot which is rotating into the place where `node` was.
Node storage parent = index.nodes[originalRoot.parent];
// figure out if we're a left or right child and have the
// parent point to the new node.
if (parent.left == originalRoot.nodeId) {
parent.left = newRoot.nodeId;
}
if (parent.right == originalRoot.nodeId) {
parent.right = newRoot.nodeId;
}
}
if (newRoot.left != 0) {
// If the new root had a left child, that moves to be the
// new right child of the original root node
Node storage leftChild = index.nodes[newRoot.left];
originalRoot.right = leftChild.nodeId;
leftChild.parent = originalRoot.nodeId;
}
// Update the newRoot's left node to point at the original node.
originalRoot.parent = newRoot.nodeId;
newRoot.left = originalRoot.nodeId;
if (newRoot.parent == 0x0) {
index.root = newRoot.nodeId;
}
// TODO: are both of these updates necessary?
_updateNodeHeight(index, originalRoot.nodeId);
_updateNodeHeight(index, newRoot.nodeId);
}
function _rotateRight(Index storage index, bytes32 nodeId) internal {
Node storage originalRoot = index.nodes[nodeId];
if (originalRoot.left == 0x0) {
// Cannot rotate right if there is no left node to rotate into
// place.
throw;
}
// The left child is taking the place of node, so we update it's
// parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left];
newRoot.parent = originalRoot.parent;
// Null out the originalRoot.left
originalRoot.left = 0x0;
if (originalRoot.parent != 0x0) {
// If the node has a parent, update the correct child to point
// at the newRoot now.
Node storage parent = index.nodes[originalRoot.parent];
if (parent.left == originalRoot.nodeId) {
parent.left = newRoot.nodeId;
}
if (parent.right == originalRoot.nodeId) {
parent.right = newRoot.nodeId;
}
}
if (newRoot.right != 0x0) {
Node storage rightChild = index.nodes[newRoot.right];
originalRoot.left = newRoot.right;
rightChild.parent = originalRoot.nodeId;
}
// Update the new root's right node to point to the original node.
originalRoot.parent = newRoot.nodeId;
newRoot.right = originalRoot.nodeId;
if (newRoot.parent == 0x0) {
index.root = newRoot.nodeId;
}
// Recompute heights.
_updateNodeHeight(index, originalRoot.nodeId);
_updateNodeHeight(index, newRoot.nodeId);
}
}
/// @title Grove - queryable indexes for ordered data.
/// @author Piper Merriam <pipermerriam@gmail.com>
contract Grove {
/*
* Indexes for ordered data
*
* Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
*/
// Map index_id to index
mapping (bytes32 => GroveLib.Index) index_lookup;
// Map node_id to index_id.
mapping (bytes32 => bytes32) node_to_index;
/// @notice Computes the id for a Grove index which is sha3(owner, indexName)
/// @param owner The address of the index owner.
/// @param indexName The name of the index.
function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
return GroveLib.computeIndexId(owner, indexName);
}
/// @notice Computes the id for a node in a given Grove index which is sha3(indexId, id)
/// @param indexId The id for the index the node belongs to.
/// @param id The unique identifier for the data this node represents.
function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
return GroveLib.computeNodeId(indexId, id);
}
/*
* Node getters
*/
/// @notice Retrieves the name of an index.
/// @param indexId The id of the index.
function getIndexName(bytes32 indexId) constant returns (bytes32) {
return index_lookup[indexId].name;
}
/// @notice Retrieves the id of the root node for this index.
/// @param indexId The id of the index.
function getIndexRoot(bytes32 indexId) constant returns (bytes32) {
return index_lookup[indexId].root;
}
/// @dev Retrieve the unique identifier this node represents.
/// @param nodeId The id for the node
function getNodeId(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeId(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the index id for the node.
/// @param nodeId The id for the node
function getNodeIndexId(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeIndexId(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the value of the node.
/// @param nodeId The id for the node
function getNodeValue(bytes32 nodeId) constant returns (int) {
return GroveLib.getNodeValue(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the height of the node.
/// @param nodeId The id for the node
function getNodeHeight(bytes32 nodeId) constant returns (uint) {
return GroveLib.getNodeHeight(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the parent id of the node.
/// @param nodeId The id for the node
function getNodeParent(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeParent(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the left child id of the node.
/// @param nodeId The id for the node
function getNodeLeftChild(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeLeftChild(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the right child id of the node.
/// @param nodeId The id for the node
function getNodeRightChild(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeRightChild(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Retrieve the id of the node that comes immediately before this
* one. Returns 0x0 if there is no previous node.
*/
/// @param nodeId The id for the node
function getPreviousNode(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getPreviousNode(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Retrieve the id of the node that comes immediately after this
* one. Returns 0x0 if there is no previous node.
*/
/// @param nodeId The id for the node
function getNextNode(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNextNode(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Update or Insert a data element represented by the unique
* identifier `id` into the index.
*/
/// @param indexName The human readable name for the index that the node should be upserted into.
/// @param id The unique identifier that the index node represents.
/// @param value The number which represents this data elements total ordering.
function insert(bytes32 indexName, bytes32 id, int value) public {
bytes32 indexId = computeIndexId(msg.sender, indexName);
var index = index_lookup[indexId];
if (index.name != indexName) {
// If this is a new index, store it's name and id
index.name = indexName;
index.id = indexId;
}
// Store the mapping from nodeId to the indexId
node_to_index[computeNodeId(indexId, id)] = indexId;
GroveLib.insert(index, id, value);
}
/// @dev Query whether a node exists within the specified index for the unique identifier.
/// @param indexId The id for the index.
/// @param id The unique identifier of the data element.
function exists(bytes32 indexId, bytes32 id) constant returns (bool) {
return GroveLib.exists(index_lookup[indexId], id);
}
/// @dev Remove the index node for the given unique identifier.
/// @param indexName The name of the index.
/// @param id The unique identifier of the data element.
function remove(bytes32 indexName, bytes32 id) public {
GroveLib.remove(index_lookup[computeIndexId(msg.sender, indexName)], id);
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param indexId The id of the index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(bytes32 indexId, bytes2 operator, int value) public returns (bytes32) {
return GroveLib.query(index_lookup[indexId], operator, value);
}
}
|
Retrieve the node id of the next node in the tree. index The index that the node is part of. nodeId The id for the node to be looked up. Unknown node, just return 0x0; Trace left to latest child in left tree. Now we trace back up through parent relationships, looking for a link where the child is the right child of it's parent.
|
function getPreviousNode(Index storage index, bytes32 nodeId) constant returns (bytes32) {
Node storage currentNode = index.nodes[nodeId];
if (currentNode.nodeId == 0x0) {
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.nodeId;
}
if (currentNode.parent != 0x0) {
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.nodeId) {
return parent.nodeId;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
}
| 5,545,924
|
pragma solidity >=0.5.0 <0.6.0;
import "./ParamUtils.sol";
import "./TradeUtils.sol";
import "./ERC1724/ZkAssetMintable.sol";
/**
* @title ZkAssetTradeable
* @author Paul Pham
* @dev A contract defining the standard interface and behaviours of a confidential tradeable asset.
* Inherits from ZkAssetMintable, only overrides confidentialTransfer
* Copyright Democracy.js 2019. All rights reserved.
**/
contract ZkAssetTradeable is ZkAssetMintable {
event UpdateTotalMinted(bytes32 noteHash, bytes noteData);
address public owner;
constructor(
address _aceAddress,
address _linkedTokenAddress,
uint256 _scalingFactor,
bool _canAdjustSupply,
bool _canConvert
) public ZkAssetMintable(
_aceAddress,
_linkedTokenAddress,
_scalingFactor,
_canAdjustSupply,
_canConvert
) {
owner = msg.sender;
}
/**
* @dev Executes one side of a confidential trade of AZTEC notes using a cached validated
* proof only.
* Accepts _proofOutput, so that multiple trades can be batched together,
* and submits them to the validateProofByHash() function of the Cryptography Engine
* to enable gas-free validation and make use of previous validation by
* seller and bidder (required).
*
* Currently only supports one proof
* TODO: loop over all proofs to validateProofByHash
* Copied from ZkAssetMintable.confidentialTransfer in aztec/protocol 0.9.1
* changing _proofData to _proofOutputs. In 1.0.0 version, we can make use of
* confidentialTransferInternal.
*
* Upon successful completion, it will update note registry states, making
* the new output nodes spendable by seller and bidder and destroying the
* old input notes.
*
* @param _proofOutputs - bytes variable outputted from proof construction
* as `expectedOutput`.
*/
function confidentialTrade(
bytes memory _proofOutputs,
bytes memory _signatures,
bytes memory _proofData,
address _transferer
) public {
bytes memory proofOutput = TradeUtils.getProofOutput(_proofOutputs, 0);
bytes memory formattedProofOutput = ParamUtils.sliceBytes(
proofOutput,
32,
proofOutput.length
);
bytes32 proofHash = keccak256(formattedProofOutput);
require( ace.validateProofByHash(
JOIN_SPLIT_PROOF, proofHash, _transferer
), "proof output is invalid for confidential transfer" );
(,
,
,
int256 publicValue) = proofOutput.extractProofOutput();
(
,
uint256 scalingFactor,
uint256 totalSupply,
,
,
,
) = ace.getRegistry(address(this));
if (publicValue > 0) {
if (totalSupply < uint256(publicValue)) {
uint256 supplementValue = uint256(publicValue).sub(totalSupply);
ERC20Mintable(address(linkedToken)).mint(address(this), supplementValue.mul(scalingFactor));
ERC20Mintable(address(linkedToken)).approve(address(ace), supplementValue.mul(scalingFactor));
ace.supplementTokens(supplementValue);
}
}
// It seems like there should be a confidentialBurn here too
confidentialTransferInternal(_proofOutputs, _signatures, _proofData);
}
}
|
Accepts _proofOutput, so that multiple trades can be batched together, and submits them to the validateProofByHash() function of the Cryptography Engine to enable gas-free validation and make use of previous validation by seller and bidder (required). Currently only supports one proof TODO: loop over all proofs to validateProofByHash Copied from ZkAssetMintable.confidentialTransfer in aztec/protocol 0.9.1 changing _proofData to _proofOutputs. In 1.0.0 version, we can make use of confidentialTransferInternal. Upon successful completion, it will update note registry states, making the new output nodes spendable by seller and bidder and destroying the old input notes. _proofOutputs - bytes variable outputted from proof construction as `expectedOutput`./
|
function confidentialTrade(
bytes memory _proofOutputs,
bytes memory _signatures,
bytes memory _proofData,
address _transferer
) public {
bytes memory proofOutput = TradeUtils.getProofOutput(_proofOutputs, 0);
bytes memory formattedProofOutput = ParamUtils.sliceBytes(
proofOutput,
32,
proofOutput.length
);
bytes32 proofHash = keccak256(formattedProofOutput);
require( ace.validateProofByHash(
JOIN_SPLIT_PROOF, proofHash, _transferer
), "proof output is invalid for confidential transfer" );
(,
,
,
int256 publicValue) = proofOutput.extractProofOutput();
(
,
uint256 scalingFactor,
uint256 totalSupply,
,
,
,
) = ace.getRegistry(address(this));
if (publicValue > 0) {
if (totalSupply < uint256(publicValue)) {
uint256 supplementValue = uint256(publicValue).sub(totalSupply);
ERC20Mintable(address(linkedToken)).mint(address(this), supplementValue.mul(scalingFactor));
ERC20Mintable(address(linkedToken)).approve(address(ace), supplementValue.mul(scalingFactor));
ace.supplementTokens(supplementValue);
}
}
confidentialTransferInternal(_proofOutputs, _signatures, _proofData);
}
| 7,244,987
|
pragma solidity ^0.4.25;
/*
SuperCountries War Game #2 - Nuke countries and share a huge war chest
SuperCountries Original Game #1 - Each player earns ether forever
███████╗██╗ ██╗██████╗ ███████╗██████╗
██╔════╝██║ ██║██╔══██╗██╔════╝██╔══██╗
███████╗██║ ██║██████╔╝█████╗ ██████╔╝
╚════██║██║ ██║██╔═══╝ ██╔══╝ ██╔══██╗
███████║╚██████╔╝██║ ███████╗██║ ██║
╚══════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
██████╗ ██████╗ ██╗ ██╗███╗ ██╗████████╗██████╗ ██╗███████╗███████╗
██╔════╝██╔═══██╗██║ ██║████╗ ██║╚══██╔══╝██╔══██╗██║██╔════╝██╔════╝
██║ ██║ ██║██║ ██║██╔██╗ ██║ ██║ ██████╔╝██║█████╗ ███████╗
██║ ██║ ██║██║ ██║██║╚██╗██║ ██║ ██╔══██╗██║██╔══╝ ╚════██║
╚██████╗╚██████╔╝╚██████╔╝██║ ╚████║ ██║ ██║ ██║██║███████╗███████║
╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚══════╝
██╗ ██╗ █████╗ ██████╗
██║ ██║██╔══██╗██╔══██╗
█████╗ ██║ █╗ ██║███████║██████╔╝ █████╗
╚════╝ ██║███╗██║██╔══██║██╔══██╗ ╚════╝
╚███╔███╔╝██║ ██║██║ ██║
╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝
© 2018 SuperCountries
所有权 - 4CE434B6058EC7C24889EC2512734B5DBA26E39891C09DF50C3CE3191CE9C51E
Xuxuxu - LB - Xufo - MyPartridge
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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 subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
///// /////
///// CALLING EXTERNAL CONTRACTS /////
///// /////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
////////////////////////////////////////////////
/// SUPERCOUNTRIES CONTRACT FUNCTIONS ///
////////////////////////////////////////////////
contract SuperCountriesExternal {
using SafeMath for uint256;
function ownerOf(uint256) public pure returns (address) { }
function priceOf(uint256) public pure returns (uint256) { }
}
////////////////////////////////////////////////////////////
/// SUPERCOUNTRIES TROPHY CARDS CONTRACT FUNCTIONS ///
////////////////////////////////////////////////////////////
contract SuperCountriesTrophyCardsExternal {
using SafeMath for uint256;
function countTrophyCards() public pure returns (uint256) { }
function getTrophyCardIdFromIndex(uint256) public pure returns (uint256) { }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
///// /////
///// SUPERCOUNTRIES WAR - NEW CONTRACT /////
///// /////
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
contract SuperCountriesWar {
using SafeMath for uint256;
////////////////////////////
/// CONSTRUCTOR ///
////////////////////////////
constructor () public {
owner = msg.sender;
continentKing.length = 16;
newOwner.length = 256;
nukerAddress.length = 256;
}
address public owner;
////////////////////////////////
/// USEFUL MODIFIERS ///
////////////////////////////////
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
/**
* @dev Throws if called by address 0x0
*/
modifier onlyRealAddress() {
require(msg.sender != address(0));
_;
}
/**
* @dev Can only be called when a game is running / unpaused
*/
modifier onlyGameNOTPaused() {
require(gameRunning == true);
_;
}
/**
* @dev Can only be called when a game is paused / ended
*/
modifier onlyGamePaused() {
require(gameRunning == false);
_;
}
///////////////////////////////////////
/// TROPHY CARDS FUNCTIONS ///
///////////////////////////////////////
///Update the index of the next trophy card to get dividends, after each buy a new card will get divs
function nextTrophyCardUpdateAndGetOwner() internal returns (address){
uint256 cardsLength = getTrophyCount();
address trophyCardOwner;
if (nextTrophyCardToGetDivs < cardsLength){
uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs);
trophyCardOwner = getCountryOwner(nextCard);
}
/// Update for next time
if (nextTrophyCardToGetDivs.add(1) < cardsLength){
nextTrophyCardToGetDivs++;
}
else nextTrophyCardToGetDivs = 0;
return trophyCardOwner;
}
/// Get the address of the owner of the "next trophy card to get divs"
function getNextTrophyCardOwner()
public
view
returns (
address nextTrophyCardOwner_,
uint256 nextTrophyCardIndex_,
uint256 nextTrophyCardId_
)
{
uint256 cardsLength = getTrophyCount();
address trophyCardOwner;
if (nextTrophyCardToGetDivs < cardsLength){
uint256 nextCard = getTrophyFromIndex(nextTrophyCardToGetDivs);
trophyCardOwner = getCountryOwner(nextCard);
}
return (
trophyCardOwner,
nextTrophyCardToGetDivs,
nextCard
);
}
////////////////////////////////////////////////////////
/// CALL OF OTHER SUPERCOUNTRIES CONTRACTS ///
////////////////////////////////////////////////////////
/// EXTERNAL VALUES
address private contractSC = 0xdf203118A954c918b967a94E51f3570a2FAbA4Ac; /// SuperCountries Original game
address private contractTrophyCards = 0xEaf763328604e6e54159aba7bF1394f2FbcC016e; /// SuperCountries Trophy Cards
SuperCountriesExternal SC = SuperCountriesExternal(contractSC);
SuperCountriesTrophyCardsExternal SCTrophy = SuperCountriesTrophyCardsExternal(contractTrophyCards);
////////////////////////////////////////////////////
/// GET FUNCTIONS FROM EXTERNAL CONTRACTS ///
////////////////////////////////////////////////////
/// SuperCountries Original
function getCountryOwner(uint256 _countryId) public view returns (address){
return SC.ownerOf(_countryId);
}
/// SuperCountries Original
function getPriceOfCountry(uint256 _countryId) public view returns (uint256){
return SC.priceOf(_countryId);
}
/// SuperCountries Trophy Cards
function getTrophyFromIndex(uint256 _index) public view returns (uint256){
return SCTrophy.getTrophyCardIdFromIndex(_index);
}
/// SuperCountries Trophy Cards
function getTrophyCount() public view returns (uint256){
return SCTrophy.countTrophyCards();
}
////////////////////////////////////////
/// VARIABLES & MAPPINGS ///
////////////////////////////////////////
/// Game enabled?
bool private gameRunning;
uint256 private gameVersion = 1; /// game Id
/// Dates & timestamps
uint256 private jackpotTimestamp; /// if this timestamp is reached, the jackpot can be shared
mapping(uint256 => bool) private thisJackpotIsPlayedAndNotWon; /// true if currently played and not won, false if already won or not yet played
/// *** J A C K P O T *** ///
/// Unwithdrawn jackpot per winner
mapping(uint256 => mapping(address => uint256)) private winnersJackpot;
mapping(uint256 => uint256) private winningCountry; /// List of winning countries
/// Payable functions prices: nuke a country, become a king ///
uint256 private startingPrice = 1e16; /// ETHER /// First raw price to nuke a country /// nuke = nextPrice (or startingPrice) + kCountry*LastKnownCountryPrice
mapping(uint256 => uint256) private nextPrice; /// ETHER /// Current raw price to nuke a country /// nuke = nextPrice + kCountry*LastKnownCountryPrice
uint256 private kingPrice = 9e15; /// ETHER /// Current king price
/// Factors ///
uint256 private kCountry = 4; /// PERCENTS /// nuke = nextPrice + kCountry*LastKnownCountryPrice (4 = 4%)
uint256 private kCountryLimit = 5e17; /// ETHER /// kCountry * lastKnownPrice cannot exceed this limit
uint256 private kNext = 1037; /// PERTHOUSAND /// price increase after each nuke (1037 = 3.7% increase)
uint256 private maxFlips = 16; /// king price will increase after maxFlips kings
uint256 private continentFlips; /// Current kings flips
uint256 private kKings = 101; /// king price increase (101 = 1% increase)
/// Kings //
address[] private continentKing;
/// Nukers ///
address[] private nukerAddress;
/// Lovers ///
struct LoverStructure {
mapping(uint256 => mapping(address => uint256)) loves; /// howManyNuked => lover address => number of loves
mapping(uint256 => uint256) maxLoves; /// highest number of loves for this country
address bestLover; /// current best lover for this country (highest number of loves)
}
mapping(uint256 => mapping(uint256 => LoverStructure)) private loversSTR; /// GameVersion > CountryId > LoverStructure
uint256 private mostLovedCountry; /// The mostLovedCountry cannot be nuked if > 4 countries on the map
mapping(address => uint256) private firstLove; /// timestamp for loves
mapping(address => uint256) private remainingLoves; /// remaining loves for today
uint256 private freeRemainingLovesPerDay = 2; /// Number of free loves per day sub 1
/// Cuts in perthousand /// the rest = potCut
uint256 private devCut = 280; /// Including riddles and medals rewards
uint256 private playerCut = 20; /// trophy card, best lover & country owner
uint256 private potCutSuperCountries = 185;
/// Jackpot redistribution /// 10 000 = 100%
uint256 private lastNukerShare = 5000;
uint256 private winningCountryShare = 4400; /// if 1 country stands, the current owner takes it all, otherwise shared between owners of remaining countries (of the winning continent)
uint256 private continentShare = 450;
uint256 private freePlayerShare = 150;
/// Minimal jackpot guarantee /// Initial funding by SuperCountries
uint256 private lastNukerMin = 3e18; /// 3 ethers
uint256 private countryOwnerMin = 3e18; /// 3 ethers
uint256 private continentMin = 1e18; /// 1 ether
uint256 private freePlayerMin = 1e18; /// 1 ether
uint256 private withdrawMinOwner; /// Dev can withdraw his initial funding if the jackpot equals this value.
/// Trophy cards
uint256 private nextTrophyCardToGetDivs; /// returns next trophy card INDEX to get dividends
/// Countries ///
uint256 private allCountriesLength = 256; /// how many countries
mapping(uint256 => mapping(uint256 => bool)) private eliminated; /// is this country eliminated? gameVersion > countryId > bool
uint256 private howManyEliminated; /// how many eliminated countries
uint256 private howManyNuked; /// how many nuked countries
uint256 private howManyReactivated; /// players are allowed to reactivate 1 country for 8 nukes
uint256 private lastNukedCountry; /// last nuked country ID
mapping(uint256 => uint256) lastKnownCountryPrice; ///
address[] private newOwner; /// Latest known country owners /// A new buyer must send at least one love or reanimate its country to be in the array
/// Continents ///
mapping(uint256 => uint256) private countryToContinent; /// country Id to Continent Id
/// Time (seconds) ///
uint256 public SLONG = 86400; /// 1 day
uint256 public DLONG = 172800; /// 2 days
uint256 public DSHORT = 14400; /// 4 hrs
////////////////////////
/// EVENTS ///
////////////////////////
/// Pause / UnPause
event PausedOrUnpaused(uint256 indexed blockTimestamp_, bool indexed gameRunning_);
/// New Game ///
event NewGameLaunched(uint256 indexed gameVersion_, uint256 indexed blockTimestamp_, address indexed msgSender_, uint256 jackpotTimestamp_);
event ErrorCountry(uint256 indexed countryId_);
/// Updates ///
event CutsUpdated(uint256 indexed newDevcut_, uint256 newPlayercut_, uint256 newJackpotCountriescut_, uint256 indexed blockTimestamp_);
event ConstantsUpdated(uint256 indexed newStartPrice_, uint256 indexed newkKingPrice_, uint256 newKNext_, uint256 newKCountry_, uint256 newKLimit_, uint256 newkKings, uint256 newMaxFlips);
event NewContractAddress(address indexed newAddress_);
event NewValue(uint256 indexed code_, uint256 indexed newValue_, uint256 indexed blockTimestamp_);
event NewCountryToContinent(uint256 indexed countryId_, uint256 indexed continentId_, uint256 indexed blockTimestamp_);
/// Players Events ///
event PlayerEvent(uint256 indexed eventCode_, uint256 indexed countryId_, address indexed player_, uint256 timestampNow_, uint256 customValue_, uint256 gameId_);
event Nuked(address indexed player_, uint256 indexed lastNukedCountry_, uint256 priceToPay_, uint256 priceRaw_);
event Reactivation(uint256 indexed countryId_, uint256 indexed howManyReactivated_);
event NewKingContinent(address indexed player_, uint256 indexed continentId_, uint256 priceToPay_);
event newMostLovedCountry(uint256 indexed countryId_, uint256 indexed maxLovesBest_);
event NewBestLover(address indexed lover_, uint256 indexed countryId_, uint256 maxLovesBest_);
event NewLove(address indexed lover_, uint256 indexed countryId_, uint256 playerLoves_, uint256 indexed gameId_, uint256 nukeCount_);
event LastCountryStanding(uint256 indexed countryId_, address indexed player_, uint256 contractBalance_, uint256 indexed gameId_, uint256 jackpotTimestamp);
event ThereIsANewOwner(address indexed newOwner_, uint256 indexed countryId_);
/// Payments ///
event CutsPaidInfos(uint256 indexed blockTimestamp_, uint256 indexed countryId_, address countryOwner_, address trophyCardOwner_, address bestLover_);
event CutsPaidValue(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, uint256 indexed SuperCountriesCut_);
event CutsPaidLight(uint256 indexed blockTimestamp_, uint256 indexed paidPrice_, uint256 thisBalance_, uint256 devCut_, uint256 playerCut_, address trophyCardOwner_, uint256 indexed SuperCountriesCut_);
event NewKingPrice(uint256 indexed kingPrice_, uint256 indexed kKings_);
/// Jackpot & Withdraws ///
event NewJackpotTimestamp(uint256 indexed jackpotTimestamp_, uint256 indexed timestamp_);
event WithdrawByDev(uint256 indexed blockTimestamp_, uint256 indexed withdrawn_, uint256 indexed withdrawMinOwner_, uint256 jackpot_);
event WithdrawJackpot(address indexed winnerAddress_, uint256 indexed jackpotToTransfer_, uint256 indexed gameVersion_);
event JackpotDispatch(address indexed winner, uint256 indexed jackpotShare_, uint256 customValue_, bytes32 indexed customText_);
event JackpotDispatchAll(uint256 indexed gameVersion_, uint256 indexed winningCountry_, uint256 indexed continentId_, uint256 timestampNow_, uint256 jackpotTimestamp_, uint256 pot_,uint256 potDispatched_, uint256 thisBalance);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////
/// PUBLIC GET FUNCTIONS ///
////////////////////////////
/// Checks if a player can nuke or be a king
function canPlayTimestamp() public view returns (bool ok_){
uint256 timestampNow = block.timestamp;
uint256 jT = jackpotTimestamp;
bool canPlayTimestamp_;
if (timestampNow < jT || timestampNow > jT.add(DSHORT)){
canPlayTimestamp_ = true;
}
return canPlayTimestamp_;
}
/// When eliminated, the country cannot be eliminated again unless someone rebuys this country
function isEliminated(uint256 _countryId) public view returns (bool isEliminated_){
return eliminated[gameVersion][_countryId];
}
/// The player can love few times a day (or more if loved yesterday)
function canPlayerLove(address _player) public view returns (bool playerCanLove_){
if (firstLove[_player].add(SLONG) > block.timestamp && remainingLoves[_player] == 0){
bool canLove = false;
} else canLove = true;
return canLove;
}
/// To reanimate a country, a player must rebuy it first on the marketplace then click the reanima button
/// Reanimations are limited: 1 allowed for 8 nukes ; disallowed if only 8 countries on the map
function canPlayerReanimate(
uint256 _countryId,
address _player
)
public
view
returns (bool canReanimate_)
{
if (
(lastKnownCountryPrice[_countryId] < getPriceOfCountry(_countryId)) &&
(isEliminated(_countryId) == true) &&
(_countryId != lastNukedCountry) &&
(block.timestamp.add(SLONG) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT)) &&
(allCountriesLength.sub(howManyEliminated) > 8) && /// If only 8 countries left, no more reactivation allowed even if other requires could allow
((howManyReactivated.add(1)).mul(8) < howManyNuked) && /// 1 reactivation for 8 Nukes
(lastKnownCountryPrice[_countryId] > 0) &&
(_player == getCountryOwner(_countryId))
) {
bool canReanima = true;
} else canReanima = false;
return canReanima;
}
/// Get the current gameVersion
function constant_getGameVersion() public view returns (uint256 currentGameVersion_){
return gameVersion;
}
/// Returns some useful informations for a country
function country_getInfoForCountry(uint256 _countryId)
public
view
returns (
bool eliminatedBool_,
uint256 whichContinent_,
address currentBestLover_,
uint256 maxLovesForTheBest_,
address countryOwner_,
uint256 lastKnownPrice_
)
{
LoverStructure storage c = loversSTR[gameVersion][_countryId];
if (eliminated[gameVersion][_countryId]){uint256 nukecount = howManyNuked.sub(1);} else nukecount = howManyNuked;
return (
eliminated[gameVersion][_countryId],
countryToContinent[_countryId],
c.bestLover,
c.maxLoves[nukecount],
newOwner[_countryId],
lastKnownCountryPrice[_countryId]
);
}
/// Returns the number of loves
function loves_getLoves(uint256 _countryId, address _player) public view returns (uint256 loves_) {
LoverStructure storage c = loversSTR[gameVersion][_countryId];
return c.loves[howManyNuked][_player];
}
/// Returns the number of loves of a player for a country for an old gameId for howManyNukedId (loves reset after each nuke)
function loves_getOldLoves(
uint256 _countryId,
address _player,
uint256 _gameId,
uint256 _oldHowManyNuked
)
public
view
returns (uint256 loves_)
{
return loversSTR[_gameId][_countryId].loves[_oldHowManyNuked][_player];
}
/// Calculate how many loves left for a player for today
function loves_getPlayerInfo(address _player)
public
view
returns (
uint256 playerFirstLove_,
uint256 playerRemainingLoves_,
uint256 realRemainingLoves_
)
{
uint256 timestampNow = block.timestamp;
uint256 firstLoveAdd24 = firstLove[_player].add(SLONG);
uint256 firstLoveAdd48 = firstLove[_player].add(DLONG);
uint256 remainStored = remainingLoves[_player];
/// This player loved today but has some loves left, remainingLoves are correct
if (firstLoveAdd24 > timestampNow && remainStored > 0){
uint256 remainReal = remainStored;
}
/// This player loved yesterday but not today, he can love "howManyEliminated.div(4)" + "freeRemainingLovesPerDay + 1" times today
else if (firstLoveAdd24 < timestampNow && firstLoveAdd48 > timestampNow){
remainReal = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay).add(1);
}
/// This player didn't love for 48h, he can love "freeRemainingLovesPerDay + 1" today
else if (firstLoveAdd48 < timestampNow){
remainReal = freeRemainingLovesPerDay.add(1);
}
else remainReal = 0;
return (
firstLove[_player],
remainStored,
remainReal
);
}
/// Returns the unwithdrawn jackpot of a player for a GameId
function player_getPlayerJackpot(
address _player,
uint256 _gameId
)
public
view
returns (
uint256 playerNowPot_,
uint256 playerOldPot_
)
{
return (
winnersJackpot[gameVersion][_player],
winnersJackpot[_gameId][_player]
);
}
/// Returns informations for a country for previous games
function country_getOldInfoForCountry(uint256 _countryId, uint256 _gameId)
public
view
returns (
bool oldEliminatedBool_,
uint256 oldMaxLovesForTheBest_
)
{
LoverStructure storage c = loversSTR[_gameId][_countryId];
return (
eliminated[_gameId][_countryId],
c.maxLoves[howManyNuked]
);
}
/// Returns informations for a country for previous games requiring more parameters
function loves_getOldNukesMaxLoves(
uint256 _countryId,
uint256 _gameId,
uint256 _howManyNuked
)
public view returns (uint256 oldMaxLovesForTheBest2_)
{
return (loversSTR[_gameId][_countryId].maxLoves[_howManyNuked]);
}
/// Returns other informations for a country for previous games
function country_getCountriesGeneralInfo()
public
view
returns (
uint256 lastNuked_,
address lastNukerAddress_,
uint256 allCountriesLength_,
uint256 howManyEliminated_,
uint256 howManyNuked_,
uint256 howManyReactivated_,
uint256 mostLovedNation_
)
{
return (
lastNukedCountry,
nukerAddress[lastNukedCountry],
allCountriesLength,
howManyEliminated,
howManyNuked,
howManyReactivated,
mostLovedCountry
);
}
/// Get the address of the king for a continent
function player_getKingOne(uint256 _continentId) public view returns (address king_) {
return continentKing[_continentId];
}
/// Return all kings
function player_getKingsAll() public view returns (address[] _kings) {
uint256 kingsLength = continentKing.length;
address[] memory kings = new address[](kingsLength);
uint256 kingsCounter = 0;
for (uint256 i = 0; i < kingsLength; i++) {
kings[kingsCounter] = continentKing[i];
kingsCounter++;
}
return kings;
}
/// Return lengths of arrays
function constant_getLength()
public
view
returns (
uint256 kingsLength_,
uint256 newOwnerLength_,
uint256 nukerLength_
)
{
return (
continentKing.length,
newOwner.length,
nukerAddress.length
);
}
/// Return the nuker's address - If a country was nuked twice (for example after a reanimation), we store the last nuker only
function player_getNuker(uint256 _countryId) public view returns (address nuker_) {
return nukerAddress[_countryId];
}
/// How many countries were nuked by a player?
/// Warning: if a country was nuked twice (for example after a reanimation), only the last nuker counts
function player_howManyNuked(address _player) public view returns (uint256 nukeCount_) {
uint256 counter = 0;
for (uint256 i = 0; i < nukerAddress.length; i++) {
if (nukerAddress[i] == _player) {
counter++;
}
}
return counter;
}
/// Which countries were nuked by a player?
function player_getNukedCountries(address _player) public view returns (uint256[] myNukedCountriesIds_) {
uint256 howLong = player_howManyNuked(_player);
uint256[] memory myNukedCountries = new uint256[](howLong);
uint256 nukeCounter = 0;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (nukerAddress[i] == _player){
myNukedCountries[nukeCounter] = i;
nukeCounter++;
}
if (nukeCounter == howLong){break;}
}
return myNukedCountries;
}
/// Which percentage of the jackpot will the winners share?
function constant_getPriZZZes()
public
view
returns (
uint256 lastNukeShare_,
uint256 countryOwnShare_,
uint256 contintShare_,
uint256 freePlayerShare_
)
{
return (
lastNukerShare,
winningCountryShare,
continentShare,
freePlayerShare
);
}
/// Returns the minimal jackpot part for each winner (if accurate)
/// Only accurate for the first game. If new games are started later, these values will be set to 0
function constant_getPriZZZesMini()
public
view
returns (
uint256 lastNukeMini_,
uint256 countryOwnMini_,
uint256 contintMini_,
uint256 freePlayerMini_,
uint256 withdrMinOwner_
)
{
return (
lastNukerMin,
countryOwnerMin,
continentMin,
freePlayerMin,
withdrawMinOwner
);
}
/// Returns some values for the current game
function constant_getPrices()
public
view
returns (
uint256 nextPrice_,
uint256 startingPrice_,
uint256 kingPrice_,
uint256 kNext_,
uint256 kCountry_,
uint256 kCountryLimit_,
uint256 kKings_)
{
return (
nextPrice[gameVersion],
startingPrice,
kingPrice,
kNext,
kCountry,
kCountryLimit,
kKings
);
}
/// Returns other values for the current game
function constant_getSomeDetails()
public
view
returns (
bool gameRunng_,
uint256 currentContractBalance_,
uint256 jackptTimstmp_,
uint256 maxFlip_,
uint256 continentFlip_,
bool jackpotNotWonYet_)
{
return (
gameRunning,
address(this).balance,
jackpotTimestamp,
maxFlips,
continentFlips,
thisJackpotIsPlayedAndNotWon[gameVersion]
);
}
/// Returns some values for previous games
function constant_getOldDetails(uint256 _gameId)
public
view
returns (
uint256 oldWinningCountry_,
bool oldJackpotBool_,
uint256 oldNextPrice_
)
{
return (
winningCountry[_gameId],
thisJackpotIsPlayedAndNotWon[_gameId],
nextPrice[_gameId]
);
}
/// Returns cuts
function constant_getCuts()
public
view
returns (
uint256 playerCut_,
uint256 potCutSC,
uint256 developerCut_)
{
return (
playerCut,
potCutSuperCountries,
devCut
);
}
/// Returns linked contracts addresses: SuperCountries core contract, Trophy Cards Contract
function constant_getContracts() public view returns (address SuperCountries_, address TrophyCards_) {
return (contractSC, contractTrophyCards);
}
/// Calculates the raw price of a next nuke
/// This value will be used to calculate a nuke price for a specified country depending of its market price
function war_getNextNukePriceRaw() public view returns (uint256 price_) {
if (nextPrice[gameVersion] != 0) {
uint256 price = nextPrice[gameVersion];
}
else price = startingPrice;
return price;
}
/// Calculates the exact price to nuke a country using the raw price (calculated above) and the market price of a country
function war_getNextNukePriceForCountry(uint256 _countryId) public view returns (uint256 priceOfThisCountry_) {
uint256 priceRaw = war_getNextNukePriceRaw();
uint256 k = lastKnownCountryPrice[_countryId].mul(kCountry).div(100);
if (k > kCountryLimit){
uint256 priceOfThisCountry = priceRaw.add(kCountryLimit);
}
else priceOfThisCountry = priceRaw.add(k);
return priceOfThisCountry;
}
/// Returns all countries for a continent
function country_getAllCountriesForContinent(uint256 _continentId) public view returns (uint256[] countries_) {
uint256 howManyCountries = country_countCountriesForContinent(_continentId);
uint256[] memory countries = new uint256[](howManyCountries);
uint256 countryCounter = 0;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (countryToContinent[i] == _continentId){
countries[countryCounter] = i;
countryCounter++;
}
if (countryCounter == howManyCountries){break;}
}
return countries;
}
/// Count all countries for a continent (standing and non standing)
function country_countCountriesForContinent(uint256 _continentId) public view returns (uint256 howManyCountries_) {
uint256 countryCounter = 0;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (countryToContinent[i] == _continentId){
countryCounter++;
}
}
return countryCounter;
}
/// Return the ID of all STANDING countries for a continent (or not Standing if FALSE)
function country_getAllStandingCountriesForContinent(
uint256 _continentId,
bool _standing
)
public
view
returns (uint256[] countries_)
{
uint256 howManyCountries = country_countStandingCountriesForContinent(_continentId, _standing);
uint256[] memory countries = new uint256[](howManyCountries);
uint256 countryCounter = 0;
uint256 gameId = gameVersion;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){
countries[countryCounter] = i;
countryCounter++;
}
if (countryCounter == howManyCountries){break;}
}
return countries;
}
/// Count all STANDING countries for a continent (or not Standing if FALSE)
function country_countStandingCountriesForContinent(
uint256 _continentId,
bool _standing
)
public
view
returns (uint256 howManyCountries_)
{
uint256 standingCountryCounter = 0;
uint256 gameId = gameVersion;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){
standingCountryCounter++;
}
}
return standingCountryCounter;
}
/// Calculate the jackpot to share between all winners
/// realJackpot: the real value to use when sharing
/// expected: this is the jackpot as we should expect if there was no minimal guarantee. It can be different from the real one if we have not reached the minimal value yet.
/// WARNING: between the real and the expected, the REAL one is the only value to use ; the expected one is for information only and will never be used in any calculation
function calculateJackpot()
public
view
returns (
uint256 nukerJackpot_,
uint256 countryJackpot_,
uint256 continentJackpot_,
uint256 freeJackpot_,
uint256 realJackpot_,
uint256 expectedJackpot_
)
{
/// If thisJackpot = false, that would mean it was already won or not yet played,
/// if true it's currently played and not won yet
if (thisJackpotIsPlayedAndNotWon[gameVersion] != true) {
uint256 nukerJPT = 0;
uint256 countryJPT = 0;
uint256 continentJPT = 0;
uint256 freeJPT = 0;
uint256 realJackpotToShare = 0;
uint256 expectedJackpotFromRates = 0;
}
else {
uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin);
expectedJackpotFromRates = ((address(this).balance).add(withdrawMinOwner).sub(devGift)).div(10000);
uint256 temp_share = expectedJackpotFromRates.mul(lastNukerShare);
if (temp_share > lastNukerMin){
nukerJPT = temp_share;
} else nukerJPT = lastNukerMin;
temp_share = expectedJackpotFromRates.mul(winningCountryShare);
if (temp_share > countryOwnerMin){
countryJPT = temp_share;
} else countryJPT = countryOwnerMin;
temp_share = expectedJackpotFromRates.mul(continentShare);
if (temp_share > continentMin){
continentJPT = temp_share;
} else continentJPT = continentMin;
temp_share = expectedJackpotFromRates.mul(freePlayerShare);
if (temp_share > freePlayerMin){
freeJPT = temp_share;
} else freeJPT = freePlayerMin;
realJackpotToShare = nukerJPT.add(countryJPT).add(continentJPT).add(freeJPT);
}
return (
nukerJPT,
countryJPT,
continentJPT,
freeJPT,
realJackpotToShare,
expectedJackpotFromRates.mul(10000)
);
}
/// Calculate how much the dev can withdraw now
/// If the dev funded a minimal guarantee, he can withdraw gradually its funding when jackpot rises up to its funding amount
function whatDevCanWithdraw() public view returns(uint256 toWithdrawByDev_){
uint256 devGift = lastNukerMin.add(countryOwnerMin).add(continentMin).add(freePlayerMin);
uint256 balance = address(this).balance;
(,,,,uint256 jackpotToDispatch,) = calculateJackpot();
uint256 leftToWithdraw = devGift.sub(withdrawMinOwner);
uint256 leftInTheContract = balance.sub(jackpotToDispatch);
if (leftToWithdraw > 0 && balance > jackpotToDispatch){
/// ok he can still withdraw
if (leftInTheContract > leftToWithdraw){
uint256 devToWithdraw = leftToWithdraw;
} else devToWithdraw = leftInTheContract;
}
return devToWithdraw;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////
/// INTERNAL FUNCTIONS ///
//////////////////////////
/// Heavy pay function for Nukes ///
function payCuts(
uint256 _value,
uint256 _balance,
uint256 _countryId,
uint256 _timestamp
)
internal
{
require(_value <= _balance);
require(_value != 0);
/// Get the next trophy card owner to send cuts
address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner();
if (nextTrophyOwner == 0) {
nextTrophyOwner = owner;
}
/// Get the country owner to send cuts
address countryOwner = newOwner[_countryId];
if (countryOwner == 0) {
countryOwner = owner;
}
/// Get the best lover to send cuts
address bestLoverToGetDivs = loversSTR[gameVersion][_countryId].bestLover;
if (bestLoverToGetDivs == 0) {
bestLoverToGetDivs = owner;
}
/// Calculate cuts
uint256 devCutPay = _value.mul(devCut).div(1000);
uint256 superCountriesPotCutPay = _value.mul(potCutSuperCountries).div(1000);
uint256 trophyAndOwnerCutPay = _value.mul(playerCut).div(1000);
/// Pay cuts ///
owner.transfer(devCutPay);
contractSC.transfer(superCountriesPotCutPay);
nextTrophyOwner.transfer(trophyAndOwnerCutPay);
countryOwner.transfer(trophyAndOwnerCutPay);
bestLoverToGetDivs.transfer(trophyAndOwnerCutPay);
emit CutsPaidInfos(_timestamp, _countryId, countryOwner, nextTrophyOwner, bestLoverToGetDivs);
emit CutsPaidValue(_timestamp, _value, address(this).balance, devCutPay, trophyAndOwnerCutPay, superCountriesPotCutPay);
assert(_balance.sub(_value) <= address(this).balance);
assert((trophyAndOwnerCutPay.mul(3).add(devCutPay).add(superCountriesPotCutPay)) < _value);
}
/// Light pay function for Kings ///
function payCutsLight(
uint256 _value,
uint256 _balance,
uint256 _timestamp
)
internal
{
require(_value <= _balance);
require(_value != 0);
/// Get the next trophy card owner to send cuts
address nextTrophyOwner = nextTrophyCardUpdateAndGetOwner();
if (nextTrophyOwner == 0) {
nextTrophyOwner = owner;
}
/// Get the last nuker to send cuts
address lastNuker = nukerAddress[lastNukedCountry];
if (lastNuker == 0) {
lastNuker = owner;
}
/// Calculate cuts
uint256 trophyCutPay = _value.mul(playerCut).div(1000);
uint256 superCountriesPotCutPay = ((_value.mul(potCutSuperCountries).div(1000)).add(trophyCutPay)).div(2); /// Divide by 2: one part for SCPot, one for lastNuker
uint256 devCutPay = (_value.mul(devCut).div(1000)).add(trophyCutPay);
/// Pay cuts ///
owner.transfer(devCutPay);
contractSC.transfer(superCountriesPotCutPay);
lastNuker.transfer(superCountriesPotCutPay);
nextTrophyOwner.transfer(trophyCutPay);
emit CutsPaidLight(_timestamp, _value, address(this).balance, devCutPay, trophyCutPay, nextTrophyOwner, superCountriesPotCutPay);
assert(_balance.sub(_value) <= address(this).balance);
assert((trophyCutPay.add(devCutPay).add(superCountriesPotCutPay)) < _value);
}
/// Refund the nuker / new king if excess
function excessRefund(
address _payer,
uint256 _priceToPay,
uint256 paidPrice
)
internal
{
uint256 excess = paidPrice.sub(_priceToPay);
if (excess > 0) {
_payer.transfer(excess);
}
}
/// Update the jackpot timestamp each time a country is nuked or a new king crowned
function updateJackpotTimestamp(uint256 _timestamp) internal {
jackpotTimestamp = _timestamp.add(604800); /// 1 week
emit NewJackpotTimestamp(jackpotTimestamp, _timestamp);
}
/// If first love > 24h, the player can love again
/// and get extra loves if loved yesterday
function updateLovesForToday(address _player, uint256 _timestampNow) internal {
uint256 firstLoveAdd24 = firstLove[_player].add(SLONG);
uint256 firstLoveAdd48 = firstLove[_player].add(DLONG);
uint256 remainV = remainingLoves[_player];
/// This player loved today but has some loves left
if (firstLoveAdd24 > _timestampNow && remainV > 0){
remainingLoves[_player] = remainV.sub(1);
}
/// This player loved yesterday but not today
else if (firstLoveAdd24 < _timestampNow && firstLoveAdd48 > _timestampNow){
remainingLoves[_player] = (howManyEliminated.div(4)).add(freeRemainingLovesPerDay);
firstLove[_player] = _timestampNow;
}
/// This player didn't love for 48h, he can love today
else if (firstLoveAdd48 < _timestampNow){
remainingLoves[_player] = freeRemainingLovesPerDay;
firstLove[_player] = _timestampNow;
}
/// This player is a zombie
else remainingLoves[_player] = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
/// WAR - PUBLIC FUNCTIONS ///
////////////////////////////////////
//////////////////////
/// NUKE A COUNTRY ///
//////////////////////
function nuke(uint256 _countryId) payable public onlyGameNOTPaused{
require(_countryId < allCountriesLength);
require(msg.value >= war_getNextNukePriceForCountry(_countryId));
require(war_getNextNukePriceForCountry(_countryId) > 0);
require(isEliminated(_countryId) == false);
require(canPlayTimestamp()); /// Impossible to nuke 2 hours after the jackpot
require(loversSTR[gameVersion][_countryId].bestLover != msg.sender); /// The best lover cannot nuke his favorite country
require(_countryId != mostLovedCountry || allCountriesLength.sub(howManyEliminated) < 5); /// We cannot nuke the mostLovedCountry if more than 4 countries stand
address player = msg.sender;
uint256 timestampNow = block.timestamp;
uint256 gameId = gameVersion;
uint256 thisBalance = address(this).balance;
uint256 priceToPay = war_getNextNukePriceForCountry(_countryId);
/// Update the latest nuker of the game in the nukerAddress array
nukerAddress[_countryId] = player;
/// Get last known price of this country for next time
uint256 lastPriceOld = lastKnownCountryPrice[_countryId];
lastKnownCountryPrice[_countryId] = getPriceOfCountry(_countryId);
/// Change the activation of this country
eliminated[gameId][_countryId] = true;
howManyEliminated++;
if (howManyEliminated.add(1) == allCountriesLength){
jackpotTimestamp = block.timestamp;
emit LastCountryStanding(_countryId, player, thisBalance, gameId, jackpotTimestamp);
}
else {
/// Update next price
uint priceRaw = war_getNextNukePriceRaw();
nextPrice[gameId] = priceRaw.mul(kNext).div(1000);
/// and update the jackpot
updateJackpotTimestamp(timestampNow);
}
lastNukedCountry = _countryId;
payCuts(priceToPay, thisBalance, _countryId, timestampNow);
excessRefund(player, priceToPay, msg.value);
howManyNuked++;
/// emit the event
emit Nuked(player, _countryId, priceToPay, priceRaw);
emit PlayerEvent(1, _countryId, player, timestampNow, howManyEliminated, gameId);
assert(lastKnownCountryPrice[_countryId] >= lastPriceOld);
}
///////////////////////////
/// REANIMATE A COUNTRY ///
///////////////////////////
function reanimateCountry(uint256 _countryId) public onlyGameNOTPaused{
require(canPlayerReanimate(_countryId, msg.sender) == true);
address player = msg.sender;
eliminated[gameVersion][_countryId] = false;
newOwner[_countryId] = player;
howManyEliminated = howManyEliminated.sub(1);
howManyReactivated++;
emit Reactivation(_countryId, howManyReactivated);
emit PlayerEvent(2, _countryId, player, block.timestamp, howManyEliminated, gameVersion);
}
/////////////////////
/// BECOME A KING ///
/////////////////////
function becomeNewKing(uint256 _continentId) payable public onlyGameNOTPaused{
require(msg.value >= kingPrice);
require(canPlayTimestamp()); /// Impossible to play 2 hours after the jackpot
address player = msg.sender;
uint256 timestampNow = block.timestamp;
uint256 gameId = gameVersion;
uint256 thisBalance = address(this).balance;
uint256 priceToPay = kingPrice;
continentKing[_continentId] = player;
updateJackpotTimestamp(timestampNow);
if (continentFlips >= maxFlips){
kingPrice = priceToPay.mul(kKings).div(100);
continentFlips = 0;
emit NewKingPrice(kingPrice, kKings);
} else continentFlips++;
payCutsLight(priceToPay, thisBalance, timestampNow);
excessRefund(player, priceToPay, msg.value);
/// emit the event
emit NewKingContinent(player, _continentId, priceToPay);
emit PlayerEvent(3, _continentId, player, timestampNow, continentFlips, gameId);
}
//////////////////////////////
/// SEND LOVE TO A COUNTRY ///
//////////////////////////////
/// Everybody can love few times a day, and get extra loves if loved yesterday
function upLove(uint256 _countryId) public onlyGameNOTPaused{
require(canPlayerLove(msg.sender));
require(_countryId < allCountriesLength);
require(!isEliminated(_countryId)); /// We cannot love an eliminated country
require(block.timestamp.add(DSHORT) < jackpotTimestamp || block.timestamp > jackpotTimestamp.add(DSHORT));
address lover = msg.sender;
address countryOwner = getCountryOwner(_countryId);
uint256 gameId = gameVersion;
LoverStructure storage c = loversSTR[gameId][_countryId];
uint256 nukecount = howManyNuked;
/// Increase the number of loves for this lover for this country
c.loves[nukecount][lover]++;
uint256 playerLoves = c.loves[nukecount][lover];
uint256 maxLovesBest = c.maxLoves[nukecount];
/// Update the bestlover if this is the case
if (playerLoves > maxLovesBest){
c.maxLoves[nukecount]++;
/// Update the mostLovedCountry
if (_countryId != mostLovedCountry && playerLoves > loversSTR[gameId][mostLovedCountry].maxLoves[nukecount]){
mostLovedCountry = _countryId;
emit newMostLovedCountry(_countryId, playerLoves);
}
/// If the best lover is a new bets lover, update
if (c.bestLover != lover){
c.bestLover = lover;
/// Send a free love to the king of this continent if he is not the best lover and remaining loves lesser than 16
address ourKing = continentKing[countryToContinent[_countryId]];
if (ourKing != lover && remainingLoves[ourKing] < 16){
remainingLoves[ourKing]++;
}
}
emit NewBestLover(lover, _countryId, playerLoves);
}
/// Update the ownership if this is the case
if (newOwner[_countryId] != countryOwner){
newOwner[_countryId] = countryOwner;
emit ThereIsANewOwner(countryOwner, _countryId);
}
/// Update the number of loves for today
updateLovesForToday(lover, block.timestamp);
/// Emit the event
emit NewLove(lover, _countryId, playerLoves, gameId, nukecount);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////
/// UPDATE FUNCTIONS ///
////////////////////////
/// Get the price of all countries before the start of the game
function storePriceOfAllCountries(uint256 _limitDown, uint256 _limitUp) public onlyOwner {
require (_limitDown < _limitUp);
require (_limitUp <= allCountriesLength);
uint256 getPrice;
address getTheOwner;
for (uint256 i = _limitDown; i < _limitUp; i++) {
getPrice = getPriceOfCountry(i);
getTheOwner = getCountryOwner(i);
lastKnownCountryPrice[i] = getPrice;
newOwner[i] = getTheOwner;
if (getPrice == 0 || getTheOwner ==0){
emit ErrorCountry(i);
}
}
}
/// Update cuts ///
/// Beware, cuts are PERTHOUSAND, not percent
function updateCuts(uint256 _newDevcut, uint256 _newPlayercut, uint256 _newSuperCountriesJackpotCut) public onlyOwner {
require(_newPlayercut.mul(3).add(_newDevcut).add(_newSuperCountriesJackpotCut) <= 700);
require(_newDevcut > 100);
devCut = _newDevcut;
playerCut = _newPlayercut;
potCutSuperCountries = _newSuperCountriesJackpotCut;
emit CutsUpdated(_newDevcut, _newPlayercut, _newSuperCountriesJackpotCut, block.timestamp);
}
/// Change nuke and kings prices and other price parameters
function updatePrices(
uint256 _newStartingPrice,
uint256 _newKingPrice,
uint256 _newKNext,
uint256 _newKCountry,
uint256 _newKLimit,
uint256 _newkKings,
uint256 _newMaxFlips
)
public
onlyOwner
{
startingPrice = _newStartingPrice;
kingPrice = _newKingPrice;
kNext = _newKNext;
kCountry = _newKCountry;
kCountryLimit = _newKLimit;
kKings = _newkKings;
maxFlips = _newMaxFlips;
emit ConstantsUpdated(_newStartingPrice, _newKingPrice, _newKNext, _newKCountry, _newKLimit, _newkKings, _newMaxFlips);
}
/// Change various parameters
function updateValue(uint256 _code, uint256 _newValue) public onlyOwner {
if (_code == 1 ){
continentKing.length = _newValue;
}
else if (_code == 2 ){
allCountriesLength = _newValue;
}
else if (_code == 3 ){
freeRemainingLovesPerDay = _newValue;
}
emit NewValue(_code, _newValue, block.timestamp);
}
/// Store countries into continents - multi countries for 1 continent function
function updateCountryToContinentMany(uint256[] _countryIds, uint256 _continentId) external onlyOwner {
for (uint256 i = 0; i < _countryIds.length; i++) {
updateCountryToContinent(_countryIds[i], _continentId);
}
}
/// Store countries into continents - 1 country for 1 continent function
function updateCountryToContinent(uint256 _countryId, uint256 _continentId) public onlyOwner {
require(_countryId < allCountriesLength);
require(_continentId < continentKing.length);
countryToContinent[_countryId] = _continentId;
emit NewCountryToContinent(_countryId, _continentId, block.timestamp);
}
/// If needed, update the external Trophy Cards contract address
function updateTCContract(address _newAddress) public onlyOwner() {
contractTrophyCards = _newAddress;
SCTrophy = SuperCountriesTrophyCardsExternal(_newAddress);
emit NewContractAddress(_newAddress);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////
/// WIN THE JACKPOT FUNCTIONS ///
/////////////////////////////////
function jackpotShareDispatch(
address _winner,
uint256 _share,
uint256 _customValue,
bytes32 _customText
)
internal
returns (uint256 shareDispatched_)
{
if (_winner == 0){
_winner = owner;
}
uint256 potDispatched = _share;
winnersJackpot[gameVersion][_winner] += _share;
emit JackpotDispatch(_winner, _share, _customValue, _customText);
return potDispatched;
}
/// Internal jackpot function for Country Owners ///
function jackpotCountryReward(uint256 _countryPot) internal returns (uint256 winningCountry_, uint256 dispatched_){
/// Is there a last standing country or not?
uint256 potDispatched;
if (howManyStandingOrNot(true) == 1){
/// There is only one country left: the winning country is the last standing country
/// And the owner of this country will not share the countryPot with other owners, all is for him!
uint256 winningCountryId = lastStanding();
address tempWinner = newOwner[winningCountryId];
potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastOwner");
}
else {
/// if else, there is more than one country standing,
/// we will reward the standing countries of the last nuked country continent
winningCountryId = lastNukedCountry;
uint256 continentId = countryToContinent[winningCountryId];
uint256[] memory standingNations = country_getAllStandingCountriesForContinent(continentId, true);
uint256 howManyCountries = standingNations.length;
/// If there is at least one standing country in this continent
if (howManyCountries > 0) {
uint256 winningCounter;
uint256 countryPotForOne = _countryPot.div(howManyCountries);
for (uint256 i = 0; i < howManyCountries && potDispatched <= _countryPot; i++) {
uint256 tempCountry = standingNations[i];
/// Get the current owner
tempWinner = newOwner[tempCountry];
potDispatched += jackpotShareDispatch(tempWinner, countryPotForOne, tempCountry, "anOwner");
winningCounter++;
if (winningCounter == howManyCountries || potDispatched.add(countryPotForOne) > _countryPot){
break;
}
}
}
/// There is no standing country in this continent, the owner of the last nuked country wins the jackpot (owner's share)
else {
tempWinner = newOwner[winningCountryId];
potDispatched = jackpotShareDispatch(tempWinner, _countryPot, winningCountryId, "lastNukedOwner");
}
}
return (winningCountryId, potDispatched);
}
/// PUBLIC JACKPOT FUNCTION TO CALL TO SHARE THE JACKPOT
/// After the jackpot, anyone can call the jackpotWIN function, it will dispatch prizes between winners
function jackpotWIN() public onlyGameNOTPaused {
require(block.timestamp > jackpotTimestamp); /// True if latestPayer + 7 days or Only one country standing
require(address(this).balance >= 1e11);
require(thisJackpotIsPlayedAndNotWon[gameVersion]); /// if true, we are currently playing this jackpot and it's not won yet
uint256 gameId = gameVersion;
/// Pause the game
gameRunning = false;
///////////////////////////////////////////////
////////// How much for the winners? //////////
///////////////////////////////////////////////
/// Calculate shares
(uint256 nukerPot, uint256 countryPot, uint256 continentPot, uint256 freePot, uint256 pot,) = calculateJackpot();
/// This jackpot is won, disable it
/// If false, this function will not be callable again
thisJackpotIsPlayedAndNotWon[gameId] = false;
////////////////////////////////////////////////////
////////// Which country won the jackpot? //////////
////////////////////////////////////////////////////
/// Dispatch shares between country owners and save the winning country ///
(uint256 winningCountryId, uint256 potDispatched) = jackpotCountryReward(countryPot);
winningCountry[gameId] = winningCountryId;
uint256 continentId = countryToContinent[winningCountryId];
////////////////////////////////////////////////
////////// Who are the other winners? //////////
////////////////////////////////////////////////
/// The king of the right continent
potDispatched += jackpotShareDispatch(continentKing[continentId], continentPot, continentId, "continent");
/// The best lover for this country
potDispatched += jackpotShareDispatch(loversSTR[gameId][winningCountryId].bestLover, freePot, 0, "free");
/// The last nuker
potDispatched += jackpotShareDispatch(nukerAddress[winningCountryId], nukerPot, 0, "nuker");
/// Emit the events ///
emit JackpotDispatchAll(gameId, winningCountryId, continentId, block.timestamp, jackpotTimestamp, pot, potDispatched, address(this).balance);
emit PausedOrUnpaused(block.timestamp, gameRunning);
/// Last check ///
assert(potDispatched <= address(this).balance);
}
/// After the sharing, all winners will be able to call this function to withdraw the won share to the their wallets
function withdrawWinners() public onlyRealAddress {
require(winnersJackpot[gameVersion][msg.sender] > 0);
address _winnerAddress = msg.sender;
uint256 gameId = gameVersion;
/// Prepare for the withdrawal
uint256 jackpotToTransfer = winnersJackpot[gameId][_winnerAddress];
winnersJackpot[gameId][_winnerAddress] = 0;
/// fire event
emit WithdrawJackpot(_winnerAddress, jackpotToTransfer, gameId);
/// Withdraw
_winnerAddress.transfer(jackpotToTransfer);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////
/// RESTART A NEW GAME ///
///////////////////////////////
/// After the jackpot, restart a new game with same settings ///
/// The owner can restart 2 hrs after the jackpot
/// If the owner doesn't restart the game 30 days after the jackpot, all players can restart the game
function restartNewGame() public onlyGamePaused{
require((msg.sender == owner && block.timestamp > jackpotTimestamp.add(DSHORT)) || block.timestamp > jackpotTimestamp.add(2629000));
uint256 timestampNow = block.timestamp;
/// Clear all values, loves, nextPrices... but bestlovers, lovers will remain
if (nextPrice[gameVersion] !=0){
gameVersion++;
lastNukedCountry = 0;
howManyNuked = 0;
howManyReactivated = 0;
howManyEliminated = 0;
lastNukerMin = 0;
countryOwnerMin = 0;
continentMin = 0;
freePlayerMin = 0;
withdrawMinOwner = 0;
kingPrice = 1e16;
newOwner.length = 0;
nukerAddress.length = 0;
newOwner.length = allCountriesLength;
nukerAddress.length = allCountriesLength;
}
/// Set new jackpot timestamp
updateJackpotTimestamp(timestampNow);
/// Restart
gameRunning = true;
thisJackpotIsPlayedAndNotWon[gameVersion] = true;
/// fire event
emit NewGameLaunched(gameVersion, timestampNow, msg.sender, jackpotTimestamp);
emit PausedOrUnpaused(block.timestamp, gameRunning);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////
/// USEFUL FUNCTIONS ///
////////////////////////
/**
* @dev Fallback function to accept all ether sent directly to the contract
* Nothing is lost, it will raise the jackpot!
*/
function() payable public { }
/// After the jackpot, the owner can restart a new game or withdraw if winners don't want their part
function withdraw() public onlyOwner {
require(block.timestamp > jackpotTimestamp.add(DSHORT) || address(this).balance <= 1e11 || whatDevCanWithdraw() > 0);
uint256 thisBalance = address(this).balance;
if (block.timestamp > jackpotTimestamp.add(DSHORT) || thisBalance <= 1e11 ){
uint256 toWithdraw = thisBalance;
}
else {
toWithdraw = whatDevCanWithdraw();
withdrawMinOwner += toWithdraw;
}
emit WithdrawByDev(block.timestamp, toWithdraw, withdrawMinOwner, thisBalance);
owner.transfer(toWithdraw);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////
/// LAST STANDING FUNCTIONS ///
///////////////////////////////
function trueStandingFalseEliminated(bool _standing) public view returns (uint256[] countries_) {
uint256 howLong = howManyStandingOrNot(_standing);
uint256[] memory countries = new uint256[](howLong);
uint256 standingCounter = 0;
uint256 gameId = gameVersion;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (eliminated[gameId][i] != _standing){
countries[standingCounter] = i;
standingCounter++;
}
if (standingCounter == howLong){break;}
}
return countries;
}
function howManyStandingOrNot(bool _standing) public view returns (uint256 howManyCountries_) {
uint256 standingCounter = 0;
uint256 gameId = gameVersion;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (eliminated[gameId][i] != _standing){
standingCounter++;
}
}
return standingCounter;
}
function lastStanding() public view returns (uint256 lastStandingNation_) {
require (howManyStandingOrNot(true) == 1);
return trueStandingFalseEliminated(true)[0];
}
}
|
Return the ID of all STANDING countries for a continent (or not Standing if FALSE)
|
function country_getAllStandingCountriesForContinent(
uint256 _continentId,
bool _standing
)
public
view
returns (uint256[] countries_)
{
uint256 howManyCountries = country_countStandingCountriesForContinent(_continentId, _standing);
uint256[] memory countries = new uint256[](howManyCountries);
uint256 countryCounter = 0;
uint256 gameId = gameVersion;
for (uint256 i = 0; i < allCountriesLength; i++) {
if (countryToContinent[i] == _continentId && eliminated[gameId][i] != _standing){
countries[countryCounter] = i;
countryCounter++;
}
}
return countries;
}
| 1,820,108
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.8.7;
interface IERC20Like {
function approve(address spender_, uint256 amount_) external returns (bool success_);
function balanceOf(address account_) external view returns (uint256 balance_);
function transfer(address recipient_, uint256 amount_) external returns (bool success_);
function transferFrom(address owner_, address recipient_, uint256 amount_) external returns (bool success_);
}
interface ILenderLike {
function poolDelegate() external view returns (address poolDelegate_);
}
interface IMapleGlobalsLike {
function investorFee() external view returns (uint256 investorFee_);
function mapleTreasury() external view returns (address mapleTreasury_);
function protocolPaused() external view returns (bool paused_);
function treasuryFee() external view returns (uint256 treasuryFee_);
}
interface IMapleProxyFactoryLike {
function mapleGlobals() external view returns (address mapleGlobals_);
function upgradeInstance(uint256 toVersion_, bytes calldata arguments_) external;
}
/// @title Small Library to standardize erc20 token interactions.
library ERC20Helper {
/**************************/
/*** Internal Functions ***/
/**************************/
function transfer(address token_, address to_, uint256 amount_) internal returns (bool success_) {
return _call(token_, abi.encodeWithSelector(IERC20Like.transfer.selector, to_, amount_));
}
function transferFrom(address token_, address from_, address to_, uint256 amount_) internal returns (bool success_) {
return _call(token_, abi.encodeWithSelector(IERC20Like.transferFrom.selector, from_, to_, amount_));
}
function approve(address token_, address spender_, uint256 amount_) internal returns (bool success_) {
// If setting approval to zero fails, return false.
if (!_call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, uint256(0)))) return false;
// If `amount_` is zero, return true as the previous step already did this.
if (amount_ == uint256(0)) return true;
// Return the result of setting the approval to `amount_`.
return _call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, amount_));
}
function _call(address token_, bytes memory data_) private returns (bool success_) {
if (token_.code.length == uint256(0)) return false;
bytes memory returnData;
( success_, returnData ) = token_.call(data_);
return success_ && (returnData.length == uint256(0) || abi.decode(returnData, (bool)));
}
}
/// @title An implementation that is to be proxied, must implement IProxied.
interface IProxied {
/**
* @dev The address of the proxy factory.
*/
function factory() external view returns (address factory_);
/**
* @dev The address of the implementation contract being proxied.
*/
function implementation() external view returns (address implementation_);
/**
* @dev Modifies the proxy's implementation address.
* @param newImplementation_ The address of an implementation contract.
*/
function setImplementation(address newImplementation_) external;
/**
* @dev Modifies the proxy's storage by delegate-calling a migrator contract with some arguments.
* Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled.
* @param migrator_ The address of a migrator contract.
* @param arguments_ Some encoded arguments to use for the migration.
*/
function migrate(address migrator_, bytes calldata arguments_) external;
}
/// @title A Maple implementation that is to be proxied, must implement IMapleProxied.
interface IMapleProxied is IProxied {
/**
* @dev The instance was upgraded.
* @param toVersion_ The new version of the loan.
* @param arguments_ The upgrade arguments, if any.
*/
event Upgraded(uint256 toVersion_, bytes arguments_);
/**
* @dev Upgrades a contract implementation to a specific version.
* Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled.
* @param toVersion_ The version to upgrade to.
* @param arguments_ Some encoded arguments to use for the upgrade.
*/
function upgrade(uint256 toVersion_, bytes calldata arguments_) external;
}
/// @title IMapleLoanEvents defines the events for a MapleLoan.
interface IMapleLoanEvents {
/**
* @dev Borrower was accepted, and set to a new account.
* @param borrower_ The address of the new borrower.
*/
event BorrowerAccepted(address indexed borrower_);
/**
* @dev Collateral was posted.
* @param amount_ The amount of collateral posted.
*/
event CollateralPosted(uint256 amount_);
/**
* @dev Collateral was removed.
* @param amount_ The amount of collateral removed.
* @param destination_ The recipient of the collateral removed.
*/
event CollateralRemoved(uint256 amount_, address indexed destination_);
/**
* @dev The loan was funded.
* @param lender_ The address of the lender.
* @param amount_ The amount funded.
* @param nextPaymentDueDate_ The due date of the next payment.
*/
event Funded(address indexed lender_, uint256 amount_, uint256 nextPaymentDueDate_);
/**
* @dev Funds were claimed.
* @param amount_ The amount of funds claimed.
* @param destination_ The recipient of the funds claimed.
*/
event FundsClaimed(uint256 amount_, address indexed destination_);
/**
* @dev Funds were drawn.
* @param amount_ The amount of funds drawn.
* @param destination_ The recipient of the funds drawn down.
*/
event FundsDrawnDown(uint256 amount_, address indexed destination_);
/**
* @dev Funds were redirected on an additional `fundLoan` call.
* @param amount_ The amount of funds redirected.
* @param destination_ The recipient of the redirected funds.
*/
event FundsRedirected(uint256 amount_, address indexed destination_);
/**
* @dev Funds were returned.
* @param amount_ The amount of funds returned.
*/
event FundsReturned(uint256 amount_);
/**
* @dev The loan was initialized.
* @param borrower_ The address of the borrower.
* @param assets_ Array of asset addresses.
* [0]: collateralAsset,
* [1]: fundsAsset.
* @param termDetails_ Array of loan parameters:
* [0]: gracePeriod,
* [1]: paymentInterval,
* [2]: payments,
* @param amounts_ Requested amounts:
* [0]: collateralRequired,
* [1]: principalRequested,
* [2]: endingPrincipal.
* @param rates_ Fee parameters:
* [0]: interestRate,
* [1]: earlyFeeRate,
* [2]: lateFeeRate,
* [3]: lateInterestPremium.
*/
event Initialized(address indexed borrower_, address[2] assets_, uint256[3] termDetails_, uint256[3] amounts_, uint256[4] rates_);
/**
* @dev Lender was accepted, and set to a new account.
* @param lender_ The address of the new lender.
*/
event LenderAccepted(address indexed lender_);
/**
* @dev Loan was repaid early and closed.
* @param principalPaid_ The portion of the total amount that went towards principal.
* @param interestPaid_ The portion of the total amount that went towards interest fees.
*/
event LoanClosed(uint256 principalPaid_, uint256 interestPaid_);
/**
* @dev A refinance was proposed.
* @param refinanceCommitment_ The hash of the refinancer and calls proposed.
* @param refinancer_ The address that will execute the refinance.
* @param calls_ The individual calls for the refinancer contract.
*/
event NewTermsAccepted(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_);
/**
* @dev A refinance was proposed.
* @param refinanceCommitment_ The hash of the refinancer and calls proposed.
* @param refinancer_ The address that will execute the refinance.
* @param calls_ The individual calls for the refinancer contract.
*/
event NewTermsProposed(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_);
/**
* @dev Payments were made.
* @param principalPaid_ The portion of the total amount that went towards principal.
* @param interestPaid_ The portion of the total amount that went towards interest fees.
*/
event PaymentMade(uint256 principalPaid_, uint256 interestPaid_);
/**
* @dev Pending borrower was set.
* @param pendingBorrower_ Address that can accept the borrower role.
*/
event PendingBorrowerSet(address pendingBorrower_);
/**
* @dev Pending lender was set.
* @param pendingLender_ Address that can accept the lender role.
*/
event PendingLenderSet(address pendingLender_);
/**
* @dev The loan was in default and funds and collateral was repossessed by the lender.
* @param collateralRepossessed_ The amount of collateral asset repossessed.
* @param fundsRepossessed_ The amount of funds asset repossessed.
* @param destination_ The recipient of the collateral and funds, if any.
*/
event Repossessed(uint256 collateralRepossessed_, uint256 fundsRepossessed_, address indexed destination_);
/**
* @dev Some token (neither fundsAsset nor collateralAsset) was removed from the loan.
* @param token_ The address of the token contract.
* @param amount_ The amount of token remove from the loan.
* @param destination_ The recipient of the token.
*/
event Skimmed(address indexed token_, uint256 amount_, address indexed destination_);
}
/// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied.
interface IMapleLoan is IMapleProxied, IMapleLoanEvents {
/***********************/
/*** State Variables ***/
/***********************/
/**
* @dev The borrower of the loan, responsible for repayments.
*/
function borrower() external view returns (address borrower_);
/**
* @dev The amount of funds that have yet to be claimed by the lender.
*/
function claimableFunds() external view returns (uint256 claimableFunds_);
/**
* @dev The amount of collateral posted against outstanding (drawn down) principal.
*/
function collateral() external view returns (uint256 collateral_);
/**
* @dev The address of the asset deposited by the borrower as collateral, if needed.
*/
function collateralAsset() external view returns (address collateralAsset_);
/**
* @dev The amount of collateral required if all of the principal required is drawn down.
*/
function collateralRequired() external view returns (uint256 collateralRequired_);
/**
* @dev The amount of funds that have yet to be drawn down by the borrower.
*/
function drawableFunds() external view returns (uint256 drawableFunds_);
/**
* @dev The rate charged at early payments.
* This value should be configured so that it is less expensive to close a loan with more than one payment remaining, but
* more expensive to close it if on the last payment.
*/
function earlyFeeRate() external view returns (uint256 earlyFeeRate_);
/**
* @dev The portion of principal to not be paid down as part of payment installments, which would need to be paid back upon final payment.
* If endingPrincipal = principal, loan is interest-only.
*/
function endingPrincipal() external view returns (uint256 endingPrincipal_);
/**
* @dev The asset deposited by the lender to fund the loan.
*/
function fundsAsset() external view returns (address fundsAsset_);
/**
* @dev The amount of time the borrower has, after a payment is due, to make a payment before being in default.
*/
function gracePeriod() external view returns (uint256 gracePeriod_);
/**
* @dev The annualized interest rate (APR), in units of 1e18, (i.e. 1% is 0.01e18).
*/
function interestRate() external view returns (uint256 interestRate_);
/**
* @dev The rate charged at late payments.
*/
function lateFeeRate() external view returns (uint256 lateFeeRate_);
/**
* @dev The premium over the regular interest rate applied when paying late.
*/
function lateInterestPremium() external view returns (uint256 lateInterestPremium_);
/**
* @dev The lender of the Loan.
*/
function lender() external view returns (address lender_);
/**
* @dev The timestamp due date of the next payment.
*/
function nextPaymentDueDate() external view returns (uint256 nextPaymentDueDate_);
/**
* @dev The specified time between loan payments.
*/
function paymentInterval() external view returns (uint256 paymentInterval_);
/**
* @dev The number of payment installments remaining for the loan.
*/
function paymentsRemaining() external view returns (uint256 paymentsRemaining_);
/**
* @dev The address of the pending borrower.
*/
function pendingBorrower() external view returns (address pendingBorrower_);
/**
* @dev The address of the pending lender.
*/
function pendingLender() external view returns (address pendingLender_);
/**
* @dev The amount of principal owed (initially, the requested amount), which needs to be paid back.
*/
function principal() external view returns (uint256 principal_);
/**
* @dev The initial principal amount requested by the borrower.
*/
function principalRequested() external view returns (uint256 principalRequested_);
/**
* @dev The factory address that deployed this contract (necessary for PoolV1 integration).
*/
function superFactory() external view returns (address superFactory_);
/********************************/
/*** State Changing Functions ***/
/********************************/
/**
* @dev Accept the borrower role, must be called by pendingBorrower.
*/
function acceptBorrower() external;
/**
* @dev Accept the lender role, must be called by pendingLender.
*/
function acceptLender() external;
/**
* @dev Accept the proposed terms ans trigger refinance execution
* @param refinancer_ The address of the refinancer contract.
* @param calls_ The encoded arguments to be passed to refinancer.
* @param amount_ An amount to pull from the caller, if any.
*/
function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external;
/**
* @dev Claim funds that have been paid (principal, interest, and late fees).
* @param amount_ The amount to be claimed.
* @param destination_ The address to send the funds.
*/
function claimFunds(uint256 amount_, address destination_) external;
/**
* @dev Repay all principal and fees and close a loan.
* @param amount_ An amount to pull from the caller, if any.
* @return principal_ The portion of the amount paid paying back principal.
* @return interest_ The portion of the amount paid paying interest fees.
*/
function closeLoan(uint256 amount_) external returns (uint256 principal_, uint256 interest_);
/**
* @dev Draw down funds from the loan.
* @param amount_ The amount to draw down.
* @param destination_ The address to send the funds.
* @return collateralPosted_ The amount of additional collateral posted, if any.
*/
function drawdownFunds(uint256 amount_, address destination_) external returns (uint256 collateralPosted_);
/**
* @dev Lend funds to the loan/borrower.
* @param lender_ The address to be registered as the lender.
* @param amount_ An amount to pull from the caller, if any.
* @return fundsLent_ The amount funded.
*/
function fundLoan(address lender_, uint256 amount_) external returns (uint256 fundsLent_);
/**
* @dev Make a payment to the loan.
* @param amount_ An amount to pull from the caller, if any.
* @return principal_ The portion of the amount paid paying back principal.
* @return interest_ The portion of the amount paid paying interest fees.
*/
function makePayment(uint256 amount_) external returns (uint256 principal_, uint256 interest_);
/**
* @dev Post collateral to the loan.
* @param amount_ An amount to pull from the caller, if any.
* @return collateralPosted_ The amount posted.
*/
function postCollateral(uint256 amount_) external returns (uint256 collateralPosted_);
/**
* @dev Propose new terms for refinance
* @param refinancer_ The address of the refinancer contract.
* @param calls_ The encoded arguments to be passed to refinancer.
*/
function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external;
/**
* @dev Remove collateral from the loan (opposite of posting collateral).
* @param amount_ The amount removed.
* @param destination_ The destination to send the removed collateral.
*/
function removeCollateral(uint256 amount_, address destination_) external;
/**
* @dev Return funds to the loan (opposite of drawing down).
* @param amount_ An amount to pull from the caller, if any.
* @return fundsReturned_ The amount returned.
*/
function returnFunds(uint256 amount_) external returns (uint256 fundsReturned_);
/**
* @dev Repossess collateral, and any funds, for a loan in default.
* @param destination_ The address where the collateral and funds asset is to be sent, if any.
* @return collateralRepossessed_ The amount of collateral asset repossessed.
* @return fundsRepossessed_ The amount of funds asset repossessed.
*/
function repossess(address destination_) external returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_);
/**
* @dev Set the pendingBorrower to a new account.
* @param pendingBorrower_ The address of the new pendingBorrower.
*/
function setPendingBorrower(address pendingBorrower_) external;
/**
* @dev Set the pendingLender to a new account.
* @param pendingLender_ The address of the new pendingLender.
*/
function setPendingLender(address pendingLender_) external;
/**
* @dev Remove some token (neither fundsAsset nor collateralAsset) from the loan.
* @param token_ The address of the token contract.
* @param destination_ The recipient of the token.
* @return skimmed_ The amount of token removed from the loan.
*/
function skim(address token_, address destination_) external returns (uint256 skimmed_);
/**********************/
/*** View Functions ***/
/**********************/
/**
* @dev Returns the excess collateral that can be removed.
* @return excessCollateral_ The excess collateral that can be removed, if any.
*/
function excessCollateral() external view returns (uint256 excessCollateral_);
/**
* @dev Get the additional collateral to be posted to drawdown some amount.
* @param drawdown_ The amount desired to be drawn down.
* @return additionalCollateral_ The additional collateral that must be posted, if any.
*/
function getAdditionalCollateralRequiredFor(uint256 drawdown_) external view returns (uint256 additionalCollateral_);
/**
* @dev Get the breakdown of the total payment needed to satisfy an early repayment.
* @return totalPrincipalAmount_ The portion of the total amount that will go towards principal.
* @return totalInterestFees_ The portion of the total amount that will go towards interest fees.
*/
function getEarlyPaymentBreakdown() external view returns (
uint256 totalPrincipalAmount_,
uint256 totalInterestFees_
);
/**
* @dev Get the breakdown of the total payment needed to satisfy `numberOfPayments` payment installments.
* @return totalPrincipalAmount_ The portion of the total amount that will go towards principal.
* @return totalInterestFees_ The portion of the total amount that will go towards interest fees.
*/
function getNextPaymentBreakdown() external view returns (
uint256 totalPrincipalAmount_,
uint256 totalInterestFees_
);
/**
* @dev Returns whether the protocol is paused.
* @return paused_ A boolean indicating if protocol is paused.
*/
function isProtocolPaused() external view returns (bool paused_);
}
abstract contract SlotManipulatable {
function _getReferenceTypeSlot(bytes32 slot_, bytes32 key_) internal pure returns (bytes32 value_) {
return keccak256(abi.encodePacked(key_, slot_));
}
function _getSlotValue(bytes32 slot_) internal view returns (bytes32 value_) {
assembly {
value_ := sload(slot_)
}
}
function _setSlotValue(bytes32 slot_, bytes32 value_) internal {
assembly {
sstore(slot_, value_)
}
}
}
/// @title An implementation that is to be proxied, will need ProxiedInternals.
abstract contract ProxiedInternals is SlotManipulatable {
/// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.factory') - 1`.
bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1);
/// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.implementation') - 1`.
bytes32 private constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc);
/// @dev Delegatecalls to a migrator contract to manipulate storage during an initialization or migration.
function _migrate(address migrator_, bytes calldata arguments_) internal virtual returns (bool success_) {
uint256 size;
assembly {
size := extcodesize(migrator_)
}
if (size == uint256(0)) return false;
( success_, ) = migrator_.delegatecall(arguments_);
}
/// @dev Sets the factory address in storage.
function _setFactory(address factory_) internal virtual returns (bool success_) {
_setSlotValue(FACTORY_SLOT, bytes32(uint256(uint160(factory_))));
return true;
}
/// @dev Sets the implementation address in storage.
function _setImplementation(address implementation_) internal virtual returns (bool success_) {
_setSlotValue(IMPLEMENTATION_SLOT, bytes32(uint256(uint160(implementation_))));
return true;
}
/// @dev Returns the factory address.
function _factory() internal view virtual returns (address factory_) {
return address(uint160(uint256(_getSlotValue(FACTORY_SLOT))));
}
/// @dev Returns the implementation address.
function _implementation() internal view virtual returns (address implementation_) {
return address(uint160(uint256(_getSlotValue(IMPLEMENTATION_SLOT))));
}
}
/// @title A Maple implementation that is to be proxied, will need MapleProxiedInternals.
abstract contract MapleProxiedInternals is ProxiedInternals {}
/// @title MapleLoanInternals defines the storage layout and internal logic of MapleLoan.
abstract contract MapleLoanInternals is MapleProxiedInternals {
uint256 private constant SCALED_ONE = uint256(10 ** 18);
// Roles
address internal _borrower; // The address of the borrower.
address internal _lender; // The address of the lender.
address internal _pendingBorrower; // The address of the pendingBorrower, the only address that can accept the borrower role.
address internal _pendingLender; // The address of the pendingLender, the only address that can accept the lender role.
// Assets
address internal _collateralAsset; // The address of the asset used as collateral.
address internal _fundsAsset; // The address of the asset used as funds.
// Loan Term Parameters
uint256 internal _gracePeriod; // The number of seconds a payment can be late.
uint256 internal _paymentInterval; // The number of seconds between payments.
// Rates
uint256 internal _interestRate; // The annualized interest rate of the loan.
uint256 internal _earlyFeeRate; // The fee rate for prematurely closing loans.
uint256 internal _lateFeeRate; // The fee rate for late payments.
uint256 internal _lateInterestPremium; // The amount to increase the interest rate by for late payments.
// Requested Amounts
uint256 internal _collateralRequired; // The collateral the borrower is expected to put up to draw down all _principalRequested.
uint256 internal _principalRequested; // The funds the borrowers wants to borrow.
uint256 internal _endingPrincipal; // The principal to remain at end of loan.
// State
uint256 internal _drawableFunds; // The amount of funds that can be drawn down.
uint256 internal _claimableFunds; // The amount of funds that the lender can claim (principal repayments, interest, etc).
uint256 internal _collateral; // The amount of collateral, in collateral asset, that is currently posted.
uint256 internal _nextPaymentDueDate; // The timestamp of due date of next payment.
uint256 internal _paymentsRemaining; // The number of payments remaining.
uint256 internal _principal; // The amount of principal yet to be paid down.
// Refinance
bytes32 internal _refinanceCommitment;
/**********************************/
/*** Internal General Functions ***/
/**********************************/
/// @dev Clears all state variables to end a loan, but keep borrower and lender withdrawal functionality intact.
function _clearLoanAccounting() internal {
_gracePeriod = uint256(0);
_paymentInterval = uint256(0);
_interestRate = uint256(0);
_earlyFeeRate = uint256(0);
_lateFeeRate = uint256(0);
_lateInterestPremium = uint256(0);
_endingPrincipal = uint256(0);
_nextPaymentDueDate = uint256(0);
_paymentsRemaining = uint256(0);
_principal = uint256(0);
}
/**
* @dev Initializes the loan.
* @param borrower_ The address of the borrower.
* @param assets_ Array of asset addresses.
* [0]: collateralAsset,
* [1]: fundsAsset.
* @param termDetails_ Array of loan parameters:
* [0]: gracePeriod,
* [1]: paymentInterval,
* [2]: payments,
* @param amounts_ Requested amounts:
* [0]: collateralRequired,
* [1]: principalRequested,
* [2]: endingPrincipal.
* @param rates_ Fee parameters:
* [0]: interestRate,
* [1]: earlyFeeRate,
* [2]: lateFeeRate,
* [3]: lateInterestPremium.
*/
function _initialize(
address borrower_,
address[2] memory assets_,
uint256[3] memory termDetails_,
uint256[3] memory amounts_,
uint256[4] memory rates_
)
internal
{
// Principal requested needs to be non-zero (see `_getCollateralRequiredFor` math).
require(amounts_[1] > uint256(0), "MLI:I:INVALID_PRINCIPAL");
// Ending principal needs to be less than or equal to principal requested.
require(amounts_[2] <= amounts_[1], "MLI:I:INVALID_ENDING_PRINCIPAL");
require((_borrower = borrower_) != address(0), "MLI:I:INVALID_BORROWER");
_collateralAsset = assets_[0];
_fundsAsset = assets_[1];
_gracePeriod = termDetails_[0];
_paymentInterval = termDetails_[1];
_paymentsRemaining = termDetails_[2];
_collateralRequired = amounts_[0];
_principalRequested = amounts_[1];
_endingPrincipal = amounts_[2];
_interestRate = rates_[0];
_earlyFeeRate = rates_[1];
_lateFeeRate = rates_[2];
_lateInterestPremium = rates_[3];
}
/**************************************/
/*** Internal Borrow-side Functions ***/
/**************************************/
/// @dev Prematurely ends a loan by making all remaining payments.
function _closeLoan() internal returns (uint256 principal_, uint256 interest_) {
require(block.timestamp <= _nextPaymentDueDate, "MLI:CL:PAYMENT_IS_LATE");
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
uint256 totalPaid = principal_ + interest_;
// The drawable funds are increased by the extra funds in the contract, minus the total needed for payment.
_drawableFunds = _drawableFunds + _getUnaccountedAmount(_fundsAsset) - totalPaid;
_claimableFunds += totalPaid;
_clearLoanAccounting();
}
/// @dev Sends `amount_` of `_drawableFunds` to `destination_`.
function _drawdownFunds(uint256 amount_, address destination_) internal {
_drawableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL");
}
/// @dev Makes a payment to progress the loan closer to maturity.
function _makePayment() internal returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
uint256 totalPaid = principal_ + interest_;
// The drawable funds are increased by the extra funds in the contract, minus the total needed for payment.
// NOTE: This line will revert if not enough funds were added for the full payment amount.
_drawableFunds = (_drawableFunds + _getUnaccountedAmount(_fundsAsset)) - totalPaid;
_claimableFunds += totalPaid;
uint256 paymentsRemaining = _paymentsRemaining;
if (paymentsRemaining == uint256(1)) {
_clearLoanAccounting(); // Assumes `_getNextPaymentBreakdown` returns a `principal_` that is `_principal`.
} else {
_nextPaymentDueDate += _paymentInterval;
_principal -= principal_;
_paymentsRemaining = paymentsRemaining - uint256(1);
}
}
/// @dev Registers the delivery of an amount of collateral to be posted.
function _postCollateral() internal returns (uint256 collateralPosted_) {
_collateral += (collateralPosted_ = _getUnaccountedAmount(_collateralAsset));
}
/// @dev Sets refinance commitment given refinance operations.
function _proposeNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 proposedRefinanceCommitment_) {
// NOTE: There is no way to invalidate the `refinanceCommitment` (i.e. bytes32(0)) without explicitly setting it if `calls_.length` is 0.
return _refinanceCommitment =
calls_.length > uint256(0)
? _getRefinanceCommitment(refinancer_, calls_)
: bytes32(0);
}
/// @dev Sends `amount_` of `_collateral` to `destination_`.
function _removeCollateral(uint256 amount_, address destination_) internal {
_collateral -= amount_;
require(ERC20Helper.transfer(_collateralAsset, destination_, amount_), "MLI:RC:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:RC:INSUFFICIENT_COLLATERAL");
}
/// @dev Registers the delivery of an amount of funds to be returned as `_drawableFunds`.
function _returnFunds() internal returns (uint256 fundsReturned_) {
_drawableFunds += (fundsReturned_ = _getUnaccountedAmount(_fundsAsset));
}
/************************************/
/*** Internal Lend-side Functions ***/
/************************************/
/// @dev Processes refinance operations.
function _acceptNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 acceptedRefinanceCommitment_) {
// NOTE: A zero refinancer address and/or empty calls array will never (probabilistically) match a refinance commitment in storage.
require(_refinanceCommitment == (acceptedRefinanceCommitment_ = _getRefinanceCommitment(refinancer_, calls_)), "MLI:ANT:COMMITMENT_MISMATCH");
require(refinancer_.code.length != uint256(0), "MLI:ANT:INVALID_REFINANCER");
// Clear refinance commitment to prevent implications of re-acceptance of another call to `_acceptNewTerms`.
_refinanceCommitment = bytes32(0);
uint256 callCount = calls_.length;
for (uint256 i; i < callCount; ++i) {
( bool success, ) = refinancer_.delegatecall(calls_[i]);
require(success, "MLI:ANT:FAILED");
}
// Ensure that collateral is maintained after changes made.
require(_isCollateralMaintained(), "MLI:ANT:INSUFFICIENT_COLLATERAL");
}
/// @dev Sends `amount_` of `_claimableFunds` to `destination_`.
/// If `amount_` is higher than `_claimableFunds` the transaction will underflow and revert.
function _claimFunds(uint256 amount_, address destination_) internal {
_claimableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:CF:TRANSFER_FAILED");
}
/// @dev Fund the loan and kick off the repayment requirements.
function _fundLoan(address lender_) internal returns (uint256 fundsLent_) {
uint256 paymentsRemaining = _paymentsRemaining;
// Can only fund loan if there are payments remaining (as defined by the initialization) and no payment is due yet (as set by a funding).
require((_nextPaymentDueDate == uint256(0)) && (paymentsRemaining != uint256(0)), "MLI:FL:LOAN_ACTIVE");
uint256 paymentInterval = _paymentInterval;
// NOTE: Don't need to check if lender_ is nonzero or valid, since it is done implicitly in calls to `lender_` below.
_lender = lender_;
_nextPaymentDueDate = block.timestamp + paymentInterval;
// Amount funded and principal are as requested.
fundsLent_ = _principal = _principalRequested;
address fundsAsset = _fundsAsset;
// Cannot under-fund loan, but over-funding results in additional funds left unaccounted for.
require(_getUnaccountedAmount(fundsAsset) >= fundsLent_, "MLI:FL:WRONG_FUND_AMOUNT");
IMapleGlobalsLike globals = IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals());
// Transfer the annualized treasury fee, if any, to the Maple treasury, and decrement drawable funds.
uint256 treasuryFee = (fundsLent_ * globals.treasuryFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000);
// Transfer delegate fee, if any, to the pool delegate, and decrement drawable funds.
uint256 delegateFee = (fundsLent_ * globals.investorFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000);
// Drawable funds is the amount funded, minus any fees.
_drawableFunds = fundsLent_ - treasuryFee - delegateFee;
require(
treasuryFee == uint256(0) || ERC20Helper.transfer(fundsAsset, globals.mapleTreasury(), treasuryFee),
"MLI:FL:T_TRANSFER_FAILED"
);
require(
delegateFee == uint256(0) || ERC20Helper.transfer(fundsAsset, ILenderLike(lender_).poolDelegate(), delegateFee),
"MLI:FL:PD_TRANSFER_FAILED"
);
}
/// @dev Reset all state variables in order to release funds and collateral of a loan in default.
function _repossess(address destination_) internal returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) {
uint256 nextPaymentDueDate = _nextPaymentDueDate;
require(
nextPaymentDueDate != uint256(0) && (block.timestamp > nextPaymentDueDate + _gracePeriod),
"MLI:R:NOT_IN_DEFAULT"
);
_clearLoanAccounting();
// Uniquely in `_repossess`, stop accounting for all funds so that they can be swept.
_collateral = uint256(0);
_claimableFunds = uint256(0);
_drawableFunds = uint256(0);
address collateralAsset = _collateralAsset;
// Either there is no collateral to repossess, or the transfer of the collateral succeeds.
require(
(collateralRepossessed_ = _getUnaccountedAmount(collateralAsset)) == uint256(0) ||
ERC20Helper.transfer(collateralAsset, destination_, collateralRepossessed_),
"MLI:R:C_TRANSFER_FAILED"
);
address fundsAsset = _fundsAsset;
// Either there are no funds to repossess, or the transfer of the funds succeeds.
require(
(fundsRepossessed_ = _getUnaccountedAmount(fundsAsset)) == uint256(0) ||
ERC20Helper.transfer(fundsAsset, destination_, fundsRepossessed_),
"MLI:R:F_TRANSFER_FAILED"
);
}
/*******************************/
/*** Internal View Functions ***/
/*******************************/
/// @dev Returns whether the amount of collateral posted is commensurate with the amount of drawn down (outstanding) principal.
function _isCollateralMaintained() internal view returns (bool isMaintained_) {
return _collateral >= _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired);
}
/// @dev Get principal and interest breakdown for paying off the entire loan early.
function _getEarlyPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) {
interest_ = ((principal_ = _principal) * _earlyFeeRate) / SCALED_ONE;
}
/// @dev Get principal and interest breakdown for next standard payment.
function _getNextPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getPaymentBreakdown(
block.timestamp,
_nextPaymentDueDate,
_paymentInterval,
_principal,
_endingPrincipal,
_paymentsRemaining,
_interestRate,
_lateFeeRate,
_lateInterestPremium
);
}
/// @dev Returns the amount of an `asset_` that this contract owns, which is not currently accounted for by its state variables.
function _getUnaccountedAmount(address asset_) internal view virtual returns (uint256 unaccountedAmount_) {
return IERC20Like(asset_).balanceOf(address(this))
- (asset_ == _collateralAsset ? _collateral : uint256(0)) // `_collateral` is `_collateralAsset` accounted for.
- (asset_ == _fundsAsset ? _claimableFunds + _drawableFunds : uint256(0)); // `_claimableFunds` and `_drawableFunds` are `_fundsAsset` accounted for.
}
/*******************************/
/*** Internal Pure Functions ***/
/*******************************/
/// @dev Returns the total collateral to be posted for some drawn down (outstanding) principal and overall collateral ratio requirement.
function _getCollateralRequiredFor(
uint256 principal_,
uint256 drawableFunds_,
uint256 principalRequested_,
uint256 collateralRequired_
)
internal pure returns (uint256 collateral_)
{
// Where (collateral / outstandingPrincipal) should be greater or equal to (collateralRequired / principalRequested).
// NOTE: principalRequested_ cannot be 0, which is reasonable, since it means this was never a loan.
return principal_ <= drawableFunds_ ? uint256(0) : (collateralRequired_ * (principal_ - drawableFunds_)) / principalRequested_;
}
/// @dev Returns principal and interest portions of a payment instalment, given generic, stateless loan parameters.
function _getInstallment(uint256 principal_, uint256 endingPrincipal_, uint256 interestRate_, uint256 paymentInterval_, uint256 totalPayments_)
internal pure virtual returns (uint256 principalAmount_, uint256 interestAmount_)
{
/*************************************************************************************************\
* | *
* A = installment amount | / \ / R \ *
* P = principal remaining | | / \ | | ----------------------- | *
* R = interest rate | A = | | P * ( 1 + R ) ^ N | - E | * | / \ | *
* N = payments remaining | | \ / | | | ( 1 + R ) ^ N | - 1 | *
* E = ending principal target | \ / \ \ / / *
* | *
* |---------------------------------------------------------------- *
* *
* - Where R is `periodicRate` *
* - Where (1 + R) ^ N is `raisedRate` *
* - Both of these rates are scaled by 1e18 (e.g., 12% => 0.12 * 10 ** 18) *
\*************************************************************************************************/
uint256 periodicRate = _getPeriodicInterestRate(interestRate_, paymentInterval_);
uint256 raisedRate = _scaledExponent(SCALED_ONE + periodicRate, totalPayments_, SCALED_ONE);
// NOTE: If a lack of precision in `_scaledExponent` results in a `raisedRate` smaller than one, assume it to be one and simplify the equation.
if (raisedRate <= SCALED_ONE) return ((principal_ - endingPrincipal_) / totalPayments_, uint256(0));
uint256 total = ((((principal_ * raisedRate) / SCALED_ONE) - endingPrincipal_) * periodicRate) / (raisedRate - SCALED_ONE);
interestAmount_ = _getInterest(principal_, interestRate_, paymentInterval_);
principalAmount_ = total >= interestAmount_ ? total - interestAmount_ : uint256(0);
}
/// @dev Returns an amount by applying an annualized and scaled interest rate, to a principal, over an interval of time.
function _getInterest(uint256 principal_, uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 interest_) {
return (principal_ * _getPeriodicInterestRate(interestRate_, interval_)) / SCALED_ONE;
}
/// @dev Returns total principal and interest portion of a number of payments, given generic, stateless loan parameters and loan state.
function _getPaymentBreakdown(
uint256 currentTime_,
uint256 nextPaymentDueDate_,
uint256 paymentInterval_,
uint256 principal_,
uint256 endingPrincipal_,
uint256 paymentsRemaining_,
uint256 interestRate_,
uint256 lateFeeRate_,
uint256 lateInterestPremium_
)
internal pure virtual
returns (uint256 principalAmount_, uint256 interestAmount_)
{
( principalAmount_, interestAmount_ ) = _getInstallment(
principal_,
endingPrincipal_,
interestRate_,
paymentInterval_,
paymentsRemaining_
);
principalAmount_ = paymentsRemaining_ == uint256(1) ? principal_ : principalAmount_;
if (currentTime_ > nextPaymentDueDate_) {
uint256 daysLate = (((currentTime_ - nextPaymentDueDate_ - 1) / 1 days) + 1) * 1 days;
interestAmount_ += _getInterest(principal_, interestRate_ + lateInterestPremium_, daysLate);
interestAmount_ += (lateFeeRate_ * principal_) / SCALED_ONE;
}
}
/// @dev Returns the interest rate over an interval, given an annualized interest rate.
function _getPeriodicInterestRate(uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 periodicInterestRate_) {
return (interestRate_ * interval_) / uint256(365 days);
}
/// @dev Returns refinance commitment given refinance parameters.
function _getRefinanceCommitment(address refinancer_, bytes[] calldata calls_) internal pure returns (bytes32 refinanceCommitment_) {
return keccak256(abi.encode(refinancer_, calls_));
}
/**
* @dev Returns exponentiation of a scaled base value.
*
* Walk through example:
* LINE | base_ | exponent_ | one_ | result_
* | 3_00 | 18 | 1_00 | 0_00
* A | 3_00 | 18 | 1_00 | 1_00
* B | 3_00 | 9 | 1_00 | 1_00
* C | 9_00 | 9 | 1_00 | 1_00
* D | 9_00 | 9 | 1_00 | 9_00
* B | 9_00 | 4 | 1_00 | 9_00
* C | 81_00 | 4 | 1_00 | 9_00
* B | 81_00 | 2 | 1_00 | 9_00
* C | 6_561_00 | 2 | 1_00 | 9_00
* B | 6_561_00 | 1 | 1_00 | 9_00
* C | 43_046_721_00 | 1 | 1_00 | 9_00
* D | 43_046_721_00 | 1 | 1_00 | 387_420_489_00
* B | 43_046_721_00 | 0 | 1_00 | 387_420_489_00
*
* Another implementation of this algorithm can be found in Dapphub's DSMath contract:
* https://github.com/dapphub/ds-math/blob/ce67c0fa9f8262ecd3d76b9e4c026cda6045e96c/src/math.sol#L77
*/
function _scaledExponent(uint256 base_, uint256 exponent_, uint256 one_) internal pure returns (uint256 result_) {
// If exponent_ is odd, set result_ to base_, else set to one_.
result_ = exponent_ & uint256(1) != uint256(0) ? base_ : one_; // A
// Divide exponent_ by 2 (overwriting itself) and proceed if not zero.
while ((exponent_ >>= uint256(1)) != uint256(0)) { // B
base_ = (base_ * base_) / one_; // C
// If exponent_ is even, go back to top.
if (exponent_ & uint256(1) == uint256(0)) continue;
// If exponent_ is odd, multiply result_ is multiplied by base_.
result_ = (result_ * base_) / one_; // D
}
}
}
/// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied.
contract MapleLoan is IMapleLoan, MapleLoanInternals {
modifier whenProtocolNotPaused() {
require(!isProtocolPaused(), "ML:PROTOCOL_PAUSED");
_;
}
/********************************/
/*** Administrative Functions ***/
/********************************/
function migrate(address migrator_, bytes calldata arguments_) external override {
require(msg.sender == _factory(), "ML:M:NOT_FACTORY");
require(_migrate(migrator_, arguments_), "ML:M:FAILED");
}
function setImplementation(address newImplementation_) external override {
require(msg.sender == _factory(), "ML:SI:NOT_FACTORY");
require(_setImplementation(newImplementation_), "ML:SI:FAILED");
}
function upgrade(uint256 toVersion_, bytes calldata arguments_) external override {
require(msg.sender == _borrower, "ML:U:NOT_BORROWER");
emit Upgraded(toVersion_, arguments_);
IMapleProxyFactoryLike(_factory()).upgradeInstance(toVersion_, arguments_);
}
/************************/
/*** Borrow Functions ***/
/************************/
function acceptBorrower() external override {
require(msg.sender == _pendingBorrower, "ML:AB:NOT_PENDING_BORROWER");
_pendingBorrower = address(0);
emit BorrowerAccepted(_borrower = msg.sender);
}
function closeLoan(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:CL:TRANSFER_FROM_FAILED");
// If the caller is not the borrower, require that the transferred amount be sufficient to close the loan without touching `_drawableFunds`.
if (msg.sender != _borrower) {
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:CL:CANNOT_USE_DRAWABLE");
}
( principal_, interest_ ) = _closeLoan();
emit LoanClosed(principal_, interest_);
}
function drawdownFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused returns (uint256 collateralPosted_) {
require(msg.sender == _borrower, "ML:DF:NOT_BORROWER");
emit FundsDrawnDown(amount_, destination_);
// Post additional collateral required to facilitate this drawdown, if needed.
uint256 additionalCollateralRequired = getAdditionalCollateralRequiredFor(amount_);
if (additionalCollateralRequired > uint256(0)) {
// Determine collateral currently unaccounted for.
uint256 unaccountedCollateral = _getUnaccountedAmount(_collateralAsset);
// Post required collateral, specifying then amount lacking as the optional amount to be transferred from.
collateralPosted_ = postCollateral(
additionalCollateralRequired > unaccountedCollateral ? additionalCollateralRequired - unaccountedCollateral : uint256(0)
);
}
_drawdownFunds(amount_, destination_);
}
function makePayment(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:MP:TRANSFER_FROM_FAILED");
// If the caller is not the borrower, require that the transferred amount be sufficient to make a payment without touching `_drawableFunds`.
if (msg.sender != _borrower) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:MP:CANNOT_USE_DRAWABLE");
}
( principal_, interest_ ) = _makePayment();
emit PaymentMade(principal_, interest_);
}
function postCollateral(uint256 amount_) public override whenProtocolNotPaused returns (uint256 collateralPosted_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(
amount_ == uint256(0) || ERC20Helper.transferFrom(_collateralAsset, msg.sender, address(this), amount_),
"ML:PC:TRANSFER_FROM_FAILED"
);
emit CollateralPosted(collateralPosted_ = _postCollateral());
}
function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:PNT:NOT_BORROWER");
emit NewTermsProposed(_proposeNewTerms(refinancer_, calls_), refinancer_, calls_);
}
function removeCollateral(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:RC:NOT_BORROWER");
emit CollateralRemoved(amount_, destination_);
_removeCollateral(amount_, destination_);
}
function returnFunds(uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsReturned_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:RF:TRANSFER_FROM_FAILED");
emit FundsReturned(fundsReturned_ = _returnFunds());
}
function setPendingBorrower(address pendingBorrower_) external override {
require(msg.sender == _borrower, "ML:SPB:NOT_BORROWER");
emit PendingBorrowerSet(_pendingBorrower = pendingBorrower_);
}
/**********************/
/*** Lend Functions ***/
/**********************/
function acceptLender() external override {
require(msg.sender == _pendingLender, "ML:AL:NOT_PENDING_LENDER");
_pendingLender = address(0);
emit LenderAccepted(_lender = msg.sender);
}
function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external override whenProtocolNotPaused {
address lenderAddress = _lender;
require(msg.sender == lenderAddress, "ML:ANT:NOT_LENDER");
address fundsAssetAddress = _fundsAsset;
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:ACT:TRANSFER_FROM_FAILED");
emit NewTermsAccepted(_acceptNewTerms(refinancer_, calls_), refinancer_, calls_);
uint256 extra = _getUnaccountedAmount(fundsAssetAddress);
// NOTE: This block ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender.
if (extra > uint256(0)) {
emit FundsRedirected(extra, lenderAddress);
require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:ANT:TRANSFER_FAILED");
}
}
function claimFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _lender, "ML:CF:NOT_LENDER");
emit FundsClaimed(amount_, destination_);
_claimFunds(amount_, destination_);
}
function fundLoan(address lender_, uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsLent_) {
address fundsAssetAddress = _fundsAsset;
// The amount specified is an optional amount to be transferred from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:FL:TRANSFER_FROM_FAILED");
// If the loan is not active, fund it.
if (_nextPaymentDueDate == uint256(0)) {
// NOTE: `_nextPaymentDueDate` emitted in event is updated by `_fundLoan`.
emit Funded(lender_, fundsLent_ = _fundLoan(lender_), _nextPaymentDueDate);
}
uint256 extra = _getUnaccountedAmount(fundsAssetAddress);
address lenderAddress = _lender;
// NOTE: This block is not only a stopgap solution to allow a LiquidityLockerV1 to send funds to a DebtLocker, while maintaining PoolV1 accounting,
// but also ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender.
if (extra > uint256(0)) {
emit FundsRedirected(extra, lenderAddress);
require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:FL:TRANSFER_FAILED");
}
}
function repossess(address destination_) external override whenProtocolNotPaused returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) {
require(msg.sender == _lender, "ML:R:NOT_LENDER");
( collateralRepossessed_, fundsRepossessed_ ) = _repossess(destination_);
emit Repossessed(collateralRepossessed_, fundsRepossessed_, destination_);
}
function setPendingLender(address pendingLender_) external override {
require(msg.sender == _lender, "ML:SPL:NOT_LENDER");
emit PendingLenderSet(_pendingLender = pendingLender_);
}
/*******************************/
/*** Miscellaneous Functions ***/
/*******************************/
function skim(address token_, address destination_) external override whenProtocolNotPaused returns (uint256 skimmed_) {
require((msg.sender == _borrower) || (msg.sender == _lender), "L:S:NO_AUTH");
require((token_ != _fundsAsset) && (token_ != _collateralAsset), "L:S:INVALID_TOKEN");
emit Skimmed(token_, skimmed_ = IERC20Like(token_).balanceOf(address(this)), destination_);
require(ERC20Helper.transfer(token_, destination_, skimmed_), "L:S:TRANSFER_FAILED");
}
/**********************/
/*** View Functions ***/
/**********************/
function getAdditionalCollateralRequiredFor(uint256 drawdown_) public view override returns (uint256 collateral_) {
// Determine the collateral needed in the contract for a reduced drawable funds amount.
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds - drawdown_, _principalRequested, _collateralRequired);
uint256 currentCollateral = _collateral;
return collateralNeeded > currentCollateral ? collateralNeeded - currentCollateral : uint256(0);
}
function getEarlyPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
}
function getNextPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
}
function isProtocolPaused() public view override returns (bool paused_) {
return IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals()).protocolPaused();
}
/****************************/
/*** State View Functions ***/
/****************************/
function borrower() external view override returns (address borrower_) {
return _borrower;
}
function claimableFunds() external view override returns (uint256 claimableFunds_) {
return _claimableFunds;
}
function collateral() external view override returns (uint256 collateral_) {
return _collateral;
}
function collateralAsset() external view override returns (address collateralAsset_) {
return _collateralAsset;
}
function collateralRequired() external view override returns (uint256 collateralRequired_) {
return _collateralRequired;
}
function drawableFunds() external view override returns (uint256 drawableFunds_) {
return _drawableFunds;
}
function earlyFeeRate() external view override returns (uint256 earlyFeeRate_) {
return _earlyFeeRate;
}
function endingPrincipal() external view override returns (uint256 endingPrincipal_) {
return _endingPrincipal;
}
function excessCollateral() external view override returns (uint256 excessCollateral_) {
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired);
uint256 currentCollateral = _collateral;
return currentCollateral > collateralNeeded ? currentCollateral - collateralNeeded : uint256(0);
}
function factory() external view override returns (address factory_) {
return _factory();
}
function fundsAsset() external view override returns (address fundsAsset_) {
return _fundsAsset;
}
function gracePeriod() external view override returns (uint256 gracePeriod_) {
return _gracePeriod;
}
function implementation() external view override returns (address implementation_) {
return _implementation();
}
function interestRate() external view override returns (uint256 interestRate_) {
return _interestRate;
}
function lateFeeRate() external view override returns (uint256 lateFeeRate_) {
return _lateFeeRate;
}
function lateInterestPremium() external view override returns (uint256 lateInterestPremium_) {
return _lateInterestPremium;
}
function lender() external view override returns (address lender_) {
return _lender;
}
function nextPaymentDueDate() external view override returns (uint256 nextPaymentDueDate_) {
return _nextPaymentDueDate;
}
function paymentInterval() external view override returns (uint256 paymentInterval_) {
return _paymentInterval;
}
function paymentsRemaining() external view override returns (uint256 paymentsRemaining_) {
return _paymentsRemaining;
}
function pendingBorrower() external view override returns (address pendingBorrower_) {
return _pendingBorrower;
}
function pendingLender() external view override returns (address pendingLender_) {
return _pendingLender;
}
function principalRequested() external view override returns (uint256 principalRequested_) {
return _principalRequested;
}
function principal() external view override returns (uint256 principal_) {
return _principal;
}
// NOTE: This is needed for `fundLoan` call from PoolV1.
function superFactory() external view override returns (address superFactory_) {
return _factory();
}
}
|
Processes refinance operations. NOTE: A zero refinancer address and/or empty calls array will never (probabilistically) match a refinance commitment in storage. Clear refinance commitment to prevent implications of re-acceptance of another call to `_acceptNewTerms`.
|
function _acceptNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 acceptedRefinanceCommitment_) {
require(_refinanceCommitment == (acceptedRefinanceCommitment_ = _getRefinanceCommitment(refinancer_, calls_)), "MLI:ANT:COMMITMENT_MISMATCH");
require(refinancer_.code.length != uint256(0), "MLI:ANT:INVALID_REFINANCER");
_refinanceCommitment = bytes32(0);
uint256 callCount = calls_.length;
for (uint256 i; i < callCount; ++i) {
( bool success, ) = refinancer_.delegatecall(calls_[i]);
require(success, "MLI:ANT:FAILED");
}
}
| 14,008,991
|
pragma solidity 0.4.24;
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract Vault is Ownable {
function () public payable {
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
function withdraw(uint amount) public onlyOwner {
require(address(this).balance >= amount);
owner.transfer(amount);
}
function withdrawAll() public onlyOwner {
withdraw(address(this).balance);
}
}
contract ERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
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;
}
}
contract TournamentPass is ERC20, Ownable {
using SafeMath for uint256;
Vault vault;
constructor(Vault _vault) public {
vault = _vault;
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
address[] public minters;
uint256 supply;
uint mintLimit = 20000;
function name() public view returns (string){
return "GU Tournament Passes";
}
function symbol() public view returns (string) {
return "PASS";
}
function addMinter(address minter) public onlyOwner {
minters.push(minter);
}
function totalSupply() public view returns (uint256) {
return supply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function isMinter(address test) internal view returns (bool) {
for (uint i = 0; i < minters.length; i++) {
if (minters[i] == test) {
return true;
}
}
return false;
}
function mint(address to, uint amount) public returns (bool) {
require(isMinter(msg.sender));
if (amount.add(supply) > mintLimit) {
return false;
}
supply = supply.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function increaseApproval(address spender, uint256 addedValue) public returns (bool) {
allowed[msg.sender][spender] = allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
function decreaseApproval(address spender, uint256 subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][spender];
if (subtractedValue > oldValue) {
allowed[msg.sender][spender] = 0;
} else {
allowed[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
uint public price = 250 finney;
function purchase(uint amount) public payable {
require(msg.value >= price.mul(amount));
require(supply.add(amount) <= mintLimit);
supply = supply.add(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
emit Transfer(address(0), msg.sender, amount);
address(vault).transfer(msg.value);
}
}
contract CappedVault is Vault {
uint public limit;
uint withdrawn = 0;
constructor() public {
limit = 33333 ether;
}
function () public payable {
require(total() + msg.value <= limit);
}
function total() public view returns(uint) {
return getBalance() + withdrawn;
}
function withdraw(uint amount) public onlyOwner {
require(address(this).balance >= amount);
owner.transfer(amount);
withdrawn += amount;
}
}
contract PreviousInterface {
function ownerOf(uint id) public view returns (address);
function getCard(uint id) public view returns (uint16, uint16);
function totalSupply() public view returns (uint);
function burnCount() public view returns (uint);
}
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 Governable {
event Pause();
event Unpause();
address public governor;
bool public paused = false;
constructor() public {
governor = msg.sender;
}
function setGovernor(address _gov) public onlyGovernor {
governor = _gov;
}
modifier onlyGovernor {
require(msg.sender == governor);
_;
}
/**
* @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() onlyGovernor whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyGovernor whenPaused public {
paused = false;
emit Unpause();
}
}
contract CardBase is Governable {
struct Card {
uint16 proto;
uint16 purity;
}
function getCard(uint id) public view returns (uint16 proto, uint16 purity) {
Card memory card = cards[id];
return (card.proto, card.purity);
}
function getShine(uint16 purity) public pure returns (uint8) {
return uint8(purity / 1000);
}
Card[] public cards;
}
contract CardProto is CardBase {
event NewProtoCard(
uint16 id, uint8 season, uint8 god,
Rarity rarity, uint8 mana, uint8 attack,
uint8 health, uint8 cardType, uint8 tribe, bool packable
);
struct Limit {
uint64 limit;
bool exists;
}
// limits for mythic cards
mapping(uint16 => Limit) public limits;
// can only set limits once
function setLimit(uint16 id, uint64 limit) public onlyGovernor {
Limit memory l = limits[id];
require(!l.exists);
limits[id] = Limit({
limit: limit,
exists: true
});
}
function getLimit(uint16 id) public view returns (uint64 limit, bool set) {
Limit memory l = limits[id];
return (l.limit, l.exists);
}
// could make these arrays to save gas
// not really necessary - will be update a very limited no of times
mapping(uint8 => bool) public seasonTradable;
mapping(uint8 => bool) public seasonTradabilityLocked;
uint8 public currentSeason;
function makeTradable(uint8 season) public onlyGovernor {
seasonTradable[season] = true;
}
function makeUntradable(uint8 season) public onlyGovernor {
require(!seasonTradabilityLocked[season]);
seasonTradable[season] = false;
}
function makePermanantlyTradable(uint8 season) public onlyGovernor {
require(seasonTradable[season]);
seasonTradabilityLocked[season] = true;
}
function isTradable(uint16 proto) public view returns (bool) {
return seasonTradable[protos[proto].season];
}
function nextSeason() public onlyGovernor {
//Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M
require(currentSeason <= 255);
currentSeason++;
mythic.length = 0;
legendary.length = 0;
epic.length = 0;
rare.length = 0;
common.length = 0;
}
enum Rarity {
Common,
Rare,
Epic,
Legendary,
Mythic
}
uint8 constant SPELL = 1;
uint8 constant MINION = 2;
uint8 constant WEAPON = 3;
uint8 constant HERO = 4;
struct ProtoCard {
bool exists;
uint8 god;
uint8 season;
uint8 cardType;
Rarity rarity;
uint8 mana;
uint8 attack;
uint8 health;
uint8 tribe;
}
// there is a particular design decision driving this:
// need to be able to iterate over mythics only for card generation
// don't store 5 different arrays: have to use 2 ids
// better to bear this cost (2 bytes per proto card)
// rather than 1 byte per instance
uint16 public protoCount;
mapping(uint16 => ProtoCard) protos;
uint16[] public mythic;
uint16[] public legendary;
uint16[] public epic;
uint16[] public rare;
uint16[] public common;
function addProtos(
uint16[] externalIDs, uint8[] gods, Rarity[] rarities, uint8[] manas, uint8[] attacks,
uint8[] healths, uint8[] cardTypes, uint8[] tribes, bool[] packable
) public onlyGovernor returns(uint16) {
for (uint i = 0; i < externalIDs.length; i++) {
ProtoCard memory card = ProtoCard({
exists: true,
god: gods[i],
season: currentSeason,
cardType: cardTypes[i],
rarity: rarities[i],
mana: manas[i],
attack: attacks[i],
health: healths[i],
tribe: tribes[i]
});
_addProto(externalIDs[i], card, packable[i]);
}
}
function addProto(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: cardType,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function addWeapon(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: WEAPON,
rarity: rarity,
mana: mana,
attack: attack,
health: durability,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: SPELL,
rarity: rarity,
mana: mana,
attack: 0,
health: 0,
tribe: 0
});
_addProto(externalID, card, packable);
}
function addMinion(
uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable
) public onlyGovernor returns(uint16) {
ProtoCard memory card = ProtoCard({
exists: true,
god: god,
season: currentSeason,
cardType: MINION,
rarity: rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
_addProto(externalID, card, packable);
}
function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal {
require(!protos[externalID].exists);
card.exists = true;
protos[externalID] = card;
protoCount++;
emit NewProtoCard(
externalID, currentSeason, card.god,
card.rarity, card.mana, card.attack,
card.health, card.cardType, card.tribe, packable
);
if (packable) {
Rarity rarity = card.rarity;
if (rarity == Rarity.Common) {
common.push(externalID);
} else if (rarity == Rarity.Rare) {
rare.push(externalID);
} else if (rarity == Rarity.Epic) {
epic.push(externalID);
} else if (rarity == Rarity.Legendary) {
legendary.push(externalID);
} else if (rarity == Rarity.Mythic) {
mythic.push(externalID);
} else {
require(false);
}
}
}
function getProto(uint16 id) public view returns(
bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) {
ProtoCard memory proto = protos[id];
return (
proto.exists,
proto.god,
proto.season,
proto.cardType,
proto.rarity,
proto.mana,
proto.attack,
proto.health,
proto.tribe
);
}
function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) {
// modulo bias is fine - creates rarity tiers etc
// will obviously revert is there are no cards of that type: this is expected - should never happen
if (rarity == Rarity.Common) {
return common[random % common.length];
} else if (rarity == Rarity.Rare) {
return rare[random % rare.length];
} else if (rarity == Rarity.Epic) {
return epic[random % epic.length];
} else if (rarity == Rarity.Legendary) {
return legendary[random % legendary.length];
} else if (rarity == Rarity.Mythic) {
// make sure a mythic is available
uint16 id;
uint64 limit;
bool set;
for (uint i = 0; i < mythic.length; i++) {
id = mythic[(random + i) % mythic.length];
(limit, set) = getLimit(id);
if (set && limit > 0){
return id;
}
}
// if not, they get a legendary :(
return legendary[random % legendary.length];
}
require(false);
return 0;
}
// can never adjust tradable cards
// each season gets a 'balancing beta'
// totally immutable: season, rarity
function replaceProto(
uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe
) public onlyGovernor {
ProtoCard memory pc = protos[index];
require(!seasonTradable[pc.season]);
protos[index] = ProtoCard({
exists: true,
god: god,
season: pc.season,
cardType: cardType,
rarity: pc.rarity,
mana: mana,
attack: attack,
health: health,
tribe: tribe
});
}
}
contract MigrationInterface {
function createCard(address user, uint16 proto, uint16 purity) public returns (uint);
function getRandomCard(CardProto.Rarity rarity, uint16 random) public view returns (uint16);
function migrate(uint id) public;
}
contract CardPackThree {
MigrationInterface public migration;
uint public creationBlock;
constructor(MigrationInterface _core) public payable {
migration = _core;
creationBlock = 5939061 + 2000; // set to creation block of first contracts + 8 hours for down time
}
event Referral(address indexed referrer, uint value, address purchaser);
/**
* purchase 'count' of this type of pack
*/
function purchase(uint16 packCount, address referrer) public payable;
// store purity and shine as one number to save users gas
function _getPurity(uint16 randOne, uint16 randTwo) internal pure returns (uint16) {
if (randOne >= 998) {
return 3000 + randTwo;
} else if (randOne >= 988) {
return 2000 + randTwo;
} else if (randOne >= 938) {
return 1000 + randTwo;
} else {
return randTwo;
}
}
}
contract FirstPheonix is Pausable {
MigrationInterface core;
constructor(MigrationInterface _core) public {
core = _core;
}
address[] public approved;
uint16 PHEONIX_PROTO = 380;
mapping(address => bool) public claimed;
function approvePack(address toApprove) public onlyOwner {
approved.push(toApprove);
}
function isApproved(address test) public view returns (bool) {
for (uint i = 0; i < approved.length; i++) {
if (approved[i] == test) {
return true;
}
}
return false;
}
// pause once cards become tradable
function claimPheonix(address user) public returns (bool){
require(isApproved(msg.sender));
if (claimed[user] || paused){
return false;
}
claimed[user] = true;
core.createCard(user, PHEONIX_PROTO, 0);
return true;
}
}
contract PresalePackThree is CardPackThree, Pausable {
CappedVault public vault;
Purchase[] public purchases;
function getPurchaseCount() public view returns (uint) {
return purchases.length;
}
struct Purchase {
uint16 current;
uint16 count;
address user;
uint randomness;
uint64 commit;
}
event PacksPurchased(uint indexed id, address indexed user, uint16 count);
event PackOpened(uint indexed id, uint16 startIndex, address indexed user, uint[] cardIDs);
event RandomnessReceived(uint indexed id, address indexed user, uint16 count, uint randomness);
constructor(MigrationInterface _core, CappedVault _vault) public payable CardPackThree(_core) {
vault = _vault;
}
function basePrice() public returns (uint);
function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity);
function packSize() public view returns (uint8) {
return 5;
}
function packsPerClaim() public view returns (uint16) {
return 15;
}
// start in bytes, length in bytes
function extract(uint num, uint length, uint start) internal pure returns (uint) {
return (((1 << (length * 8)) - 1) & (num >> ((start * 8) - 1)));
}
function purchase(uint16 packCount, address referrer) whenNotPaused public payable {
require(packCount > 0);
require(referrer != msg.sender);
uint price = calculatePrice(basePrice(), packCount);
require(msg.value >= price);
Purchase memory p = Purchase({
user: msg.sender,
count: packCount,
commit: uint64(block.number),
randomness: 0,
current: 0
});
uint id = purchases.push(p) - 1;
emit PacksPurchased(id, msg.sender, packCount);
if (referrer != address(0)) {
uint commission = price / 10;
referrer.transfer(commission);
price -= commission;
emit Referral(referrer, commission, msg.sender);
}
address(vault).transfer(price);
}
// can be called by anybody
// can miners withhold blocks --> not really
// giving up block reward for extra chance --> still really low
function callback(uint id) public {
Purchase storage p = purchases[id];
require(p.randomness == 0);
bytes32 bhash = blockhash(p.commit);
// will get the same on every block
// only use properties which can't be altered by the user
uint random = uint(keccak256(abi.encodePacked(bhash, p.user, address(this), p.count)));
// can't callback on the original block
require(uint64(block.number) != p.commit);
if (uint(bhash) == 0) {
// should never happen (must call within next 256 blocks)
// if it does, just give them 1: will become common and therefore less valuable
// set to 1 rather than 0 to avoid calling claim before randomness
p.randomness = 1;
} else {
p.randomness = random;
}
emit RandomnessReceived(id, p.user, p.count, p.randomness);
}
function claim(uint id) public {
Purchase storage p = purchases[id];
require(canClaim);
uint16 proto;
uint16 purity;
uint16 count = p.count;
uint result = p.randomness;
uint8 size = packSize();
address user = p.user;
uint16 current = p.current;
require(result != 0); // have to wait for the callback
// require(user == msg.sender); // not needed
require(count > 0);
uint[] memory ids = new uint[](size);
uint16 end = current + packsPerClaim() > count ? count : current + packsPerClaim();
require(end > current);
for (uint16 i = current; i < end; i++) {
for (uint8 j = 0; j < size; j++) {
(proto, purity) = getCardDetails(i, j, result);
ids[j] = migration.createCard(user, proto, purity);
}
emit PackOpened(id, (i * size), user, ids);
}
p.current += (end - current);
}
function predictPacks(uint id) external view returns (uint16[] protos, uint16[] purities) {
Purchase memory p = purchases[id];
uint16 proto;
uint16 purity;
uint16 count = p.count;
uint result = p.randomness;
uint8 size = packSize();
purities = new uint16[](size * count);
protos = new uint16[](size * count);
for (uint16 i = 0; i < count; i++) {
for (uint8 j = 0; j < size; j++) {
(proto, purity) = getCardDetails(i, j, result);
purities[(i * size) + j] = purity;
protos[(i * size) + j] = proto;
}
}
return (protos, purities);
}
function calculatePrice(uint base, uint16 packCount) public view returns (uint) {
// roughly 6k blocks per day
uint difference = block.number - creationBlock;
uint numDays = difference / 6000;
if (20 > numDays) {
return (base - (((20 - numDays) * base) / 100)) * packCount;
}
return base * packCount;
}
function _getCommonPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) {
if (rand == 999999) {
return CardProto.Rarity.Mythic;
} else if (rand >= 998345) {
return CardProto.Rarity.Legendary;
} else if (rand >= 986765) {
return CardProto.Rarity.Epic;
} else if (rand >= 924890) {
return CardProto.Rarity.Rare;
} else {
return CardProto.Rarity.Common;
}
}
function _getRarePlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) {
if (rand == 999999) {
return CardProto.Rarity.Mythic;
} else if (rand >= 981615) {
return CardProto.Rarity.Legendary;
} else if (rand >= 852940) {
return CardProto.Rarity.Epic;
} else {
return CardProto.Rarity.Rare;
}
}
function _getEpicPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) {
if (rand == 999999) {
return CardProto.Rarity.Mythic;
} else if (rand >= 981615) {
return CardProto.Rarity.Legendary;
} else {
return CardProto.Rarity.Epic;
}
}
function _getLegendaryPlusRarity(uint32 rand) internal pure returns (CardProto.Rarity) {
if (rand == 999999) {
return CardProto.Rarity.Mythic;
} else {
return CardProto.Rarity.Legendary;
}
}
bool public canClaim = true;
function setCanClaim(bool claim) public onlyOwner {
canClaim = claim;
}
function getComponents(
uint16 i, uint8 j, uint rand
) internal returns (
uint random, uint32 rarityRandom, uint16 purityOne, uint16 purityTwo, uint16 protoRandom
) {
random = uint(keccak256(abi.encodePacked(i, rand, j)));
rarityRandom = uint32(extract(random, 4, 10) % 1000000);
purityOne = uint16(extract(random, 2, 4) % 1000);
purityTwo = uint16(extract(random, 2, 6) % 1000);
protoRandom = uint16(extract(random, 2, 8) % (2**16-1));
return (random, rarityRandom, purityOne, purityTwo, protoRandom);
}
function withdraw() public onlyOwner {
owner.transfer(address(this).balance);
}
}
contract PackMultiplier is PresalePackThree {
address[] public packs;
uint16 public multiplier = 3;
FirstPheonix pheonix;
PreviousInterface old;
uint16 public packLimit = 5;
constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, FirstPheonix _pheonix)
public PresalePackThree(_core, vault)
{
packs = _packs;
pheonix = _pheonix;
old = _old;
}
function getCardCount() internal view returns (uint) {
return old.totalSupply() + old.burnCount();
}
function isPriorPack(address test) public view returns(bool) {
for (uint i = 0; i < packs.length; i++) {
if (packs[i] == test) {
return true;
}
}
return false;
}
event Status(uint before, uint aft);
function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) {
require(isPriorPack(pack));
uint length = getCardCount();
PresalePackThree(pack).claim(purchaseID);
uint lengthAfter = getCardCount();
require(lengthAfter > length);
uint16 cardDifference = uint16(lengthAfter - length);
require(cardDifference % 5 == 0);
uint16 packCount = cardDifference / 5;
uint16 extra = packCount * multiplier;
address lastCardOwner = old.ownerOf(lengthAfter - 1);
Purchase memory p = Purchase({
user: lastCardOwner,
count: extra,
commit: uint64(block.number),
randomness: 0,
current: 0
});
uint id = purchases.push(p) - 1;
emit PacksPurchased(id, lastCardOwner, extra);
// try to give them a first pheonix
pheonix.claimPheonix(lastCardOwner);
emit Status(length, lengthAfter);
if (packCount <= packLimit) {
for (uint i = 0; i < cardDifference; i++) {
migration.migrate(lengthAfter - 1 - i);
}
}
return (extra, lastCardOwner);
}
function setPackLimit(uint16 limit) public onlyOwner {
packLimit = limit;
}
}
contract LegendaryPackThree is PackMultiplier {
function basePrice() public returns (uint) {
return 112 finney;
}
TournamentPass public tournament;
constructor(PreviousInterface _old, address[] _packs, MigrationInterface _core, CappedVault vault, TournamentPass _tournament, FirstPheonix _pheonix)
public PackMultiplier(_old, _packs, _core, vault, _pheonix) {
tournament = _tournament;
}
function claimMultiple(address pack, uint purchaseID) public returns (uint16, address) {
uint16 extra;
address user;
(extra, user) = super.claimMultiple(pack, purchaseID);
tournament.mint(user, extra);
}
function getCardDetails(uint16 packIndex, uint8 cardIndex, uint result) public view returns (uint16 proto, uint16 purity) {
uint random;
uint32 rarityRandom;
uint16 protoRandom;
uint16 purityOne;
uint16 purityTwo;
CardProto.Rarity rarity;
(random, rarityRandom, purityOne, purityTwo, protoRandom) = getComponents(packIndex, cardIndex, result);
if (cardIndex == 4) {
rarity = _getLegendaryPlusRarity(rarityRandom);
} else if (cardIndex == 3) {
rarity = _getRarePlusRarity(rarityRandom);
} else {
rarity = _getCommonPlusRarity(rarityRandom);
}
purity = _getPurity(purityOne, purityTwo);
proto = migration.getRandomCard(rarity, protoRandom);
return (proto, purity);
}
}
|
can be called by anybody can miners withhold blocks --> not really giving up block reward for extra chance --> still really low will get the same on every block only use properties which can&39;t be altered by the user can&39;t callback on the original block should never happen (must call within next 256 blocks) if it does, just give them 1: will become common and therefore less valuable set to 1 rather than 0 to avoid calling claim before randomness
|
function callback(uint id) public {
Purchase storage p = purchases[id];
require(p.randomness == 0);
bytes32 bhash = blockhash(p.commit);
uint random = uint(keccak256(abi.encodePacked(bhash, p.user, address(this), p.count)));
require(uint64(block.number) != p.commit);
if (uint(bhash) == 0) {
p.randomness = 1;
p.randomness = random;
}
emit RandomnessReceived(id, p.user, p.count, p.randomness);
}
| 6,825,352
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./PricingCalculator.sol";
// Inspired by PIXL and Chubbies.
contract DumplingERC721 is ERC721, Ownable, PricingCalculator {
uint public constant MAX_DUMPLINGS = 2500;
bool public hasSaleStarted = true;
string public constant R = "We are nervous. Are you?";
constructor (string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol){
_setBaseURI(baseURI);
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function calculatePrice() public view returns (uint256) {
require(hasSaleStarted == true, "Sale hasn't started");
require(totalSupply() < MAX_DUMPLINGS, "No more dumplings");
uint currentSupply = totalSupply();
uint currentPrice = priceCalculator(currentSupply);
return currentPrice;
}
function calculatePriceForToken(uint _id) public view returns (uint256) {
require(_id < MAX_DUMPLINGS, "Sale has already ended");
uint currentPrice = priceCalculator(_id);
return currentPrice;
}
function startSale() public onlyOwner {
hasSaleStarted = true;
}
function pauseSale() public onlyOwner {
hasSaleStarted = false;
}
/**
* @dev Withdraw ether from this contract (Callable by owner only)
*/
function withdraw() onlyOwner public {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function steamDumplings(uint256 numDumplings) public payable {
require(SafeMath.add(totalSupply(), 1) <= MAX_DUMPLINGS, "Exceeds maximum dumpling supply.");
require(numDumplings > 0 && numDumplings <= 12, "You can steam minimum 1, maximum 12 dumpling pets");
require(msg.value >= SafeMath.mul(calculatePrice(), numDumplings), "Oh No. No dumplings for you. Amount of Ether sent is not correct.");
for (uint i = 0; i < numDumplings; i++) {
uint mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
// _setTokenURI(newTokenId, Strings.toString(newTokenId));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mecanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
contract PricingCalculator {
function priceCalculator(uint currentSupply) public view returns (uint256) {
if (currentSupply >= 2375) {
return 400000000000000000; // 2376-2500: 0.4 ETH
} else if (currentSupply >= 2250) {
return 300000000000000000; // 2251-2375: 0.3 ETH
} else if (currentSupply >= 1875) {
return 200000000000000000; // 1876-2250: 0.2 ETH
} else if (currentSupply >= 875) {
return 100000000000000000; // 876-1875: 0.1 ETH
} else if (currentSupply >= 375) {
return 50000000000000000; // 376-875: 0.05 ETH
} else if (currentSupply >= 125) {
return 40000000000000000; // 126-375: 0.04 ETH
} else {
return 30000000000000000; // 0 - 125 0.03 ETH
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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);
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals Clear metadata (if any)
|
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
| 35
|
// Sources flattened with hardhat v2.8.0 https://hardhat.org
// File contracts/erc20/IERC20.sol
// SPDX-License-Identifier: MIT
// 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 contracts/erc20/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// 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 contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File contracts/erc20/ERC20.sol
// SPDX-License-Identifier: MIT
// 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, allowance(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 = allowance(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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* 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 contracts/erc20/ERC20Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// File contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/erc20/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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'
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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/utils/Ownable.sol
// SPDX-License-Identifier: MIT
// 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 contracts/utils/Sender.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
abstract contract Sender
{
event Received(address, uint, uint256);
event Send(address, uint, uint256);
receive() external payable {
emit Received(msg.sender, msg.value, gasleft());
}
function send(address payable to) payable public {
require(msg.value >= address(this).balance, "Not enough AVAX");
to.transfer(msg.value);
emit Send(to, msg.value, gasleft());
}
}
// File contracts/MagnumOpus.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract MagnumOpus is Ownable, Sender
{
address private _gothSwap;
address private _neonArkade;
address private _courtOfTheMoon;
address private _twilightMarket;
constructor (address gothSwap_, address neonArkade_, address courtOfTheMoon_, address twilightMarket_) {
_gothSwap = gothSwap_;
_neonArkade = neonArkade_;
_courtOfTheMoon = courtOfTheMoon_;
_twilightMarket = twilightMarket_;
}
}
// File contracts/swap/pairs/IGothPair.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IGothPair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File contracts/swap/farm/EssenceERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
contract EssenceERC20 is Ownable, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
IGothPair private _gothPair;
constructor(string memory name_, string memory symbol_, IGothPair gothPair_) {
_name = name_;
_symbol = symbol_;
_gothPair = gothPair_;
}
function gothPair () public view returns (IGothPair) {
return _gothPair;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
function mint (address account, uint256 amount) public onlyOwner
{
_mint(account, amount);
}
function withdrawGSLTo (address account, uint256 amount) public onlyOwner
{
_gothPair.transfer(account, 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);
}
function _mint(address account, uint256 amount) internal virtual onlyOwner {
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);
}
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);
}
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 _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);
}
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File contracts/swap/farm/IEssenceFarm.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface IEssenceFarm
{
function baseMintRate () external view returns (uint256);
function totalUserLevels () external view returns (uint256);
function potionMaster () external view returns (address);
function emergencyBenefactor () external view returns (address);
function userInfo () external view returns (uint256[3] memory);
function farmAddress (uint256 farmId) external view returns (address);
function farmerInfo (uint256 farmId) external view returns (uint256[3] memory);
function farmCount () external view returns (uint256);
}
// File contracts/utils/SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
function sqrt(uint256 n) internal pure returns (uint256) { unchecked {
if (n > 0) {
uint256 x = n / 2 + 1;
uint256 y = (x + n / x) / 2;
while (x > y) {
x = y;
y = (x + n / x) / 2;
}
return x;
}
return 0;
} }
}
// File contracts/utils/TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending AVAX that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
}
function safeTransferAVAX(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper: AVAX_TRANSFER_FAILED");
}
}
// File contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/swap/farm/EssenceFarm.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract EssenceFarm is IEssenceFarm, Ownable, Sender, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for EssenceERC20;
// Define Structs
struct Effect {
uint256 value;
uint256 expires;
string potionId;
}
struct User {
uint256 experience;
uint256 level;
uint256 experienceRequired;
Effect expBoost;
}
struct FarmInfo {
uint256 staked;
uint256 accruedEssence;
uint256 lastInteraction;
Effect bonusYield;
Effect farmMorph;
}
struct Farm { EssenceERC20 essence; IGothPair pair; uint256 farmBonus; }
// Arrays & Mappings
mapping(address => User) private _users;
mapping(uint256 => mapping(address => FarmInfo)) _farmers;
Farm[] private _farms;
// Paramaters
uint256 private _baseMintRate;
uint256 private _totalUserLevels;
address private _potionMaster;
address private _emergencyBenefactor;
// Events
event Deposit(address sender, uint256 amount, uint256 farmId);
event Withdraw(address sender, uint256 amount, uint256 farmId);
event ClaimReward(address sender, uint256 amount, uint256 farmId);
event AddFarm(string name, string symbol, uint256 bonus, address pairAddress, uint256 farmId);
event RemoveFarm(string message, uint256 farmId);
event SetBaseMintRate(uint256 newMintRate);
event IncrementExperience(address sender, uint256 experience, uint256 level);
event SetPotionMaster(address newPotionMaster);
event InstantEssencePayout(uint256 farmId, uint256 amount, address user);
event ApplyBonusYield(uint256 farmId, uint256 bonus, uint256 expires, string potionId, address user);
event ApplyFarmMorph(uint256 farmId, uint256 morphTo, uint256 expires, string potionId, address user);
event ApplyExpBoost(uint256 farmId, uint256 boost, uint256 expires, string potionId, address user);
event SetEmergencyBenefactor(address newEmergencyBenefactor);
event EmergencyRemove(uint256 farmId, uint256 amount);
// Modifiers
modifier farmRequired(uint256 farmId) {
require(farmId <= _farms.length - 1, 'farmRequired: invalid farm id');
_;
}
modifier onlyPotionMaster() {
require(_potionMaster == _msgSender(), "onlyPotionMaster: caller is not the potion master");
_;
}
// Constructor
constructor (IGothPair gothPair_)
{
_baseMintRate = 10000000000000000000;
addFarm("Earth Essence", "EARTH", 1, gothPair_);
addFarm("Air Essence", "AIR", 1, gothPair_);
addFarm("Spirit Essence", "SPIRIT", 1, gothPair_);
addFarm("Water Essence", "WATER", 1, gothPair_);
addFarm("Fire Essence", "FIRE", 1, gothPair_);
}
// Paramater Management
function baseMintRate () external view override returns (uint256) {
return _baseMintRate;
}
function totalUserLevels () external view override returns (uint256) {
return _totalUserLevels;
}
function setBaseMintRate (uint256 newMintRate) public onlyOwner {
_baseMintRate = newMintRate;
emit SetBaseMintRate(_baseMintRate);
}
function setPotionMaster (address newPotionMaster) public onlyOwner {
_potionMaster = newPotionMaster;
emit SetPotionMaster(_potionMaster);
}
function potionMaster () external view override returns (address) {
return _potionMaster;
}
function setEmergencyBenefactor (address newEmergencyBenefactor) public onlyOwner {
_emergencyBenefactor = newEmergencyBenefactor;
emit SetEmergencyBenefactor(_emergencyBenefactor);
}
function emergencyBenefactor () external view override returns (address) {
return _emergencyBenefactor;
}
// User Management
function userInfo () external view override returns (uint256[3] memory) {
User memory user = _users[msg.sender];
uint256[3] memory info = [user.experience, user.level, user.experienceRequired];
return info;
}
function incrementExperience (address sender, uint256 reward) internal
{
User storage user = _users[sender];
uint256 exp = reward.div(1e12);
user.experience = user.experience.add(calculateExpBoost(exp, sender));
calculateLevel(sender);
emit IncrementExperience(sender, exp, user.level);
}
function calculateLevel (address sender) internal
{
User storage user = _users[sender];
if (user.experience >= user.experienceRequired)
{
user.level = user.level.add(1);
_totalUserLevels.add(1);
user.experienceRequired = user.experienceRequired.mul(12500 - (user.level.mul(225).div(100))).div(10000);
}
}
function forceLevelUpdate () external
{
calculateLevel(msg.sender);
}
function calculateExpBoost (uint256 expIn, address farmUser) internal returns (uint256)
{
User storage user = _users[farmUser];
if (block.timestamp < user.expBoost.expires)
{
return expIn.mul(user.expBoost.value);
}
else
{
user.expBoost.value = 1;
return expIn;
}
}
// Farm Management
function farmAddress (uint256 farmId) external view override returns (address) {
require(farmId <= _farms.length - 1, 'invalid farm id');
return address(_farms[farmId].essence);
}
function farmerInfo (uint256 farmId) external view override returns (uint256[3] memory) {
require(farmId <= _farms.length - 1, 'invalid farm id');
FarmInfo memory farmInfo = _farmers[farmId][msg.sender];
uint256[3] memory info = [farmInfo.staked, farmInfo.accruedEssence, farmInfo.lastInteraction];
return info;
}
function farmCount () external view override returns (uint256) {
return _farms.length;
}
function farmBalance (uint256 farmId) public view returns (uint256) {
require(farmId <= _farms.length - 1, 'invalid farm id');
return _farms[farmId].pair.balanceOf(address(_farms[farmId].essence));
}
function farmBalanceOf (uint256 farmId, address sender) public view farmRequired(farmId) returns (uint256) {
return _farms[farmId].essence.balanceOf(sender);
}
function addFarm (string memory name, string memory symbol, uint256 bonus, IGothPair pair) public onlyOwner {
require(bytes(name).length > 0, "addFarm: please provide name");
require(bytes(symbol).length > 0, "addFarm: please provide symbol");
require(bonus > 0, "addFarm: bonus cannot be 0");
_farms.push(
Farm({
essence: new EssenceERC20(name, symbol, pair),
pair: pair,
farmBonus: bonus
})
);
emit AddFarm(name, symbol, bonus, address(pair), _farms.length - 1);
}
function removeFarm (uint256 farmId) public onlyOwner farmRequired(farmId)
{
require(farmId > 4, "removeFarm: protected farm");
require(_farms[farmId].pair.balanceOf(address(_farms[farmId].essence)) <= 0, "removeFarm: farm still has GSL tokens staked");
delete _farms[farmId];
emit RemoveFarm("Farm has been removed", farmId);
}
function emergencyRemove (uint256 farmId) public farmRequired(farmId) onlyOwner returns (bool)
{
uint256 balance = farmBalance(farmId);
_farms[farmId].essence.withdrawGSLTo(_emergencyBenefactor, balance);
emit EmergencyRemove(farmId, balance);
return true;
}
// Farm Interaction
function deposit (uint256 amount, uint256 farmId) external farmRequired(farmId) nonReentrant returns (bool)
{
require(_farms[farmId].pair.balanceOf(msg.sender) >= amount, "deposit: not enough GSL tokens");
require(_farms[farmId].pair.allowance(msg.sender, address(this)) >= amount, "deposit: GSL tokens have not been approved for transfer by the sender");
FarmInfo storage farmer = _farmers[farmId][msg.sender];
User storage user = _users[msg.sender];
if (user.level == 0)
{
user.experience = 0;
user.experienceRequired = 50 * 1e18;
_totalUserLevels += 1;
user.level = 1;
}
uint256 accruedEssence = calculateRewardSinceLastTimestamp(msg.sender, farmId);
if (farmer.staked > 0)
{
farmer.accruedEssence = accruedEssence;
}
farmer.staked = farmer.staked + amount;
farmer.lastInteraction = block.timestamp;
TransferHelper.safeTransferFrom(address(_farms[farmId].pair), msg.sender, address(_farms[farmId].essence), amount);
emit Deposit(msg.sender, amount, farmId);
return true;
}
function withdraw (uint256 amount, uint256 farmId) external farmRequired(farmId) nonReentrant returns (bool)
{
FarmInfo storage farmer = _farmers[farmId][msg.sender];
require(farmer.staked >= amount, "withdraw: sender does not have that many GSL tokens staked in this farm");
if (farmer.staked == amount)
{
claimReward(msg.sender, farmId);
}
else
{
farmer.accruedEssence = farmer.accruedEssence + calculateRewardSinceLastTimestamp(msg.sender, farmId);
}
farmer.staked = farmer.staked - amount;
farmer.lastInteraction = block.timestamp;
_farms[farmId].essence.withdrawGSLTo(msg.sender, amount);
emit Withdraw(msg.sender, amount, farmId);
return true;
}
// Reward Management
function claimReward (address sender, uint256 farmId) public farmRequired(farmId)
{
FarmInfo memory farmer = _farmers[farmId][sender];
require(farmer.staked > 0, "claimReward: no GSL staked");
uint256 reward = farmer.accruedEssence + calculateRewardSinceLastTimestamp(sender, farmId);
farmer.accruedEssence = 0;
uint256 farmToMint = farmId;
if (farmer.farmMorph.expires > block.timestamp)
{
farmToMint = farmer.farmMorph.value;
}
incrementExperience(sender, reward);
_farms[farmToMint].essence.mint(sender, reward);
emit ClaimReward(sender, reward, farmId);
}
function calculateReward (uint256 farmId) external view farmRequired(farmId) returns (uint256)
{
return _farmers[farmId][msg.sender].accruedEssence + calculateRewardSinceLastTimestamp(msg.sender, farmId);
}
function calculateRewardSinceLastTimestamp (address sender, uint256 farmId) private view farmRequired(farmId) returns (uint256)
{
FarmInfo storage farmer = _farmers[farmId][sender];
if (farmer.staked > 0)
{
uint256 multiplier = block.timestamp.sub(farmer.lastInteraction);
uint256 levelMod = 1;
uint256 bonusYield = 1;
if (_totalUserLevels > _users[sender].level)
{
levelMod = _totalUserLevels.sub(_users[sender].level);
}
if (farmer.bonusYield.value > 1 && farmer.bonusYield.expires < block.timestamp)
{
bonusYield = farmer.bonusYield.value;
}
uint256 reward = (multiplier
.mul(_baseMintRate)
.mul(farmer.staked)
.div(farmBalance(farmId))
.div(levelMod)
.mul(bonusYield));
return reward;
}
else
{
return 0;
}
}
// Potion Effect Management
function instantEssencePayout (uint256 farmId, uint256 amount, address farmUser) public onlyPotionMaster farmRequired (farmId)
{
_farms[farmId].essence.mint(farmUser, amount);
emit InstantEssencePayout(farmId, amount, farmUser);
}
function applyBonusYield (uint256 farmId, uint256 bonus, uint256 expires, string memory potionId, address farmUser) public onlyPotionMaster farmRequired (farmId)
{
require(bonus > 0, "applyBonusYield: bonus cannot be 0");
FarmInfo storage farmer = _farmers[farmId][farmUser];
farmer.bonusYield.value = bonus;
farmer.bonusYield.expires = expires;
farmer.bonusYield.potionId = potionId;
emit ApplyBonusYield(farmId, bonus, expires, potionId, farmUser);
}
function applyFarmMorph (uint256 farmId, uint256 morphTo, uint256 expires, string memory potionId, address farmUser) public onlyPotionMaster farmRequired (farmId)
{
require(morphTo <= _farms.length - 1, 'applyFarmMorph: invalid farm id to morph to');
FarmInfo storage farmer = _farmers[farmId][farmUser];
farmer.farmMorph.value = morphTo;
farmer.farmMorph.expires = expires;
farmer.farmMorph.potionId = potionId;
emit ApplyFarmMorph(farmId, morphTo, expires, potionId, farmUser);
}
function applyExpBoost (uint256 farmId, uint256 boost, uint256 expires, string memory potionId, address farmUser) public onlyPotionMaster farmRequired (farmId)
{
require(boost > 0, "applyExpBoost: boost cannot be 0");
User storage user = _users[farmUser];
user.expBoost.value = boost;
user.expBoost.expires = expires;
user.expBoost.potionId = potionId;
emit ApplyExpBoost(farmId, boost, expires, potionId, farmUser);
}
}
// File contracts/swap/GothStake.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
// GothStake is a modified version of JoeBar.sol that is from Trader Joe's GitHub joe-core repository, found here;
// https://github.com/traderjoe-xyz/joe-core/blob/main/contracts/JoeBar.sol.
//
// This contract handles swapping to and from bGOTH, GOTH's staking token.
contract GothStake is ERC20("GOTH Bits", "bGOTH") {
using SafeMath for uint256;
IERC20 public goth;
// Define the GOTH token contract
constructor(IERC20 _goth) {
goth = _goth;
}
// Locks GOTH and mints bGOTH
function enter(uint256 _amount) public {
// Gets the amount of GOTH locked in the contract
uint256 totalGoth = goth.balanceOf(address(this));
// Gets the amount of bGOTH in existence
uint256 totalShares = totalSupply();
// If no bGOTH exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalGoth == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of bGOTH the GOTH is worth. The ratio will change overtime, as bGOTH is burned/minted and GOTH deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalGoth);
_mint(msg.sender, what);
}
// Lock the GOTH in the contract
goth.transferFrom(msg.sender, address(this), _amount);
}
// Unlocks the staked + gained GOTH and burns bGOTH
function leave(uint256 _share) public {
// Gets the amount of bGOTH in existence
uint256 totalShares = totalSupply();
// Calculates the amount of GOTH the bGOTH is worth
uint256 what = _share.mul(goth.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
goth.transfer(msg.sender, what);
}
}
// File contracts/swap/GothTokenV2.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract GothTokenV2 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;
constructor()
{
_name = "GOTH Token v2";
_symbol = "GOTHv2";
_mint(address(this), 1000000000 * 10 ** decimals());
}
function name() public view virtual override returns (string memory)
{
return _name;
}
function symbol() public view virtual override returns (string memory)
{
return _symbol;
}
function decimals() public view virtual override returns (uint8)
{
return 18;
}
function totalSupply() public view virtual override returns (uint256)
{
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256)
{
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function burn(uint256 amount) public virtual returns (bool)
{
_burn(_msgSender(), amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
{
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked
{
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool)
{
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked
{
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual
{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked
{
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual
{
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual
{
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked
{
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual
{
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
// File contracts/swap/GothV2Swap.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
contract GothV2Swap is GothTokenV2
{
using SafeMath for uint;
IERC20 private _oldGoth;
address private _burnAddress;
address private _owner;
constructor(IERC20 oldGoth_, address burnAddress_)
{
_oldGoth = oldGoth_;
_burnAddress = burnAddress_;
_owner = msg.sender;
}
receive() external payable { }
function owner () public view virtual returns (address)
{
return _owner;
}
function oldGoth() public view virtual returns (address)
{
return address(_oldGoth);
}
function burnAddress() public view virtual returns (address)
{
return _burnAddress;
}
function swapForNewGoth (uint256 amount) public virtual returns (bool)
{
_swapForNewGoth(msg.sender, amount);
return true;
}
function withdraw (uint256 amount) public returns (bool)
{
_withdraw(msg.sender, amount);
return true;
}
function changeOwner (address newOwner) public returns (bool)
{
_changeOwner(msg.sender, newOwner);
return true;
}
function _swapForNewGoth (address sender, uint256 amount) internal virtual
{
require(_oldGoth.balanceOf(sender) >= amount, "old goth balance too low");
require(_oldGoth.allowance(sender, address(this)) >= amount, "allowance too low");
_oldGoth.transferFrom(sender, _burnAddress, amount);
_transfer(address(this), sender, (amount.div(1000) + (amount.div(1000).div(10))));
}
function _withdraw (address sender, uint256 amount) internal virtual
{
require(sender == _owner, "denied");
require(balanceOf(address(this)) >= amount, "funds too low in contract");
_transfer(address(this), sender, amount);
}
function _changeOwner (address sender, address newOwner) internal virtual
{
require(sender == _owner, "denied");
_owner = newOwner;
}
}
// File contracts/swap/OldGothToken.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.2;
contract OldGothToken is ERC20, ERC20Burnable
{
constructor() ERC20("GOTH Token", "GOTH")
{
_mint(msg.sender, 1000000000000 * 10 ** decimals());
}
}
// File contracts/swap/pairs/IGothFactory.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IGothFactory {
//event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// File contracts/swap/pairs/IGothPairERC20.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IGothPairERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
}
// File contracts/utils/Math.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
/**
* @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 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// File contracts/utils/SafeGothMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeGothMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
// File contracts/swap/pairs/GothPairERC20.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
contract GothPairERC20 {
using SafeGothMath for uint256;
string public constant name = "GSL Tokens";
string public constant symbol = "GSL";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
uint256 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, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "GothSwap: 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, "GothSwap: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// File contracts/utils/UQ112x112.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File contracts/swap/pairs/IGothCallee.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IGothCallee {
function gothCall(
address sender,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
// File contracts/swap/pairs/GothPair.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
// GothPair is a modified version of JoePair.sol that is from Trader Joe's GitHub joe-core repository, found here;
// https://github.com/traderjoe-xyz/joe-core/blob/main/contracts/traderjoe/JoePair.so.
//
// This contract handles token pairing and liquidity pools for the GOTH Token Network.
interface IMigrator {
// Return the desired amount of liquidity token that the migrator wants.
function desiredLiquidity() external view returns (uint256);
}
contract GothPair is GothPairERC20 {
using SafeGothMath for uint256;
using UQ112x112 for uint224;
uint256 public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
modifier lock() {
require(unlocked == 1, "GothSwap: LOCKED");
unlocked = 0;
_;
unlocked = 1;
}
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(
address token,
address to,
uint256 value
) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "GothSwap: TRANSFER_FAILED");
}
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, "GothSwap: FORBIDDEN"); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 balance1,
uint112 _reserve0,
uint112 _reserve1
) private {
require(balance0 <= type(uint112).max && balance1 <= type(uint112).max, "GothSwap: OVERFLOW");
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IGothFactory(factory).feeTo();
feeOn = feeTo != address(0);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IGothPairERC20(token0).balanceOf(address(this));
uint256 balance1 = IGothPairERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
address migrator = IGothFactory(factory).migrator();
if (msg.sender == migrator) {
liquidity = IMigrator(migrator).desiredLiquidity();
require(liquidity > 0 && liquidity != type(uint256).max, "Bad desired liquidity");
} else {
require(migrator == address(0), "Must not have migrator");
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
}
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, "GothSwap: INSUFFICIENT_LIQUIDITY_MINTED");
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IGothPairERC20(_token0).balanceOf(address(this));
uint256 balance1 = IGothPairERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, "GothSwap: INSUFFICIENT_LIQUIDITY_BURNED");
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IGothPairERC20(_token0).balanceOf(address(this));
balance1 = IGothPairERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint256(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external lock {
require(amount0Out > 0 || amount1Out > 0, "GothSwap: INSUFFICIENT_OUTPUT_AMOUNT");
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, "GothSwap: INSUFFICIENT_LIQUIDITY");
uint256 balance0;
uint256 balance1;
{
// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "GothSwap: INVALID_TO");
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IGothCallee(to).gothCall(msg.sender, amount0Out, amount1Out, data);
balance0 = IGothPairERC20(_token0).balanceOf(address(this));
balance1 = IGothPairERC20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, "GothSwap: INSUFFICIENT_INPUT_AMOUNT");
{
// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), "GothSwap: K");
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IGothPairERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IGothPairERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(
IGothPairERC20(token0).balanceOf(address(this)),
IGothPairERC20(token1).balanceOf(address(this)),
reserve0,
reserve1
);
}
}
// File contracts/swap/pairs/GothFactory.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
contract GothFactory is IGothFactory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view override returns (uint256) {
return allPairs.length;
}
function pairCodeHash() external pure returns (bytes32) {
return keccak256(type(GothPair).creationCode);
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, "GothSwap: IDENTICAL_ADDRESSES");
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "GothSwap: ZERO_ADDRESS");
require(getPair[token0][token1] == address(0), "GothSwap: PAIR_EXISTS"); // single check is sufficient
bytes memory bytecode = type(GothPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
GothPair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override {
require(msg.sender == feeToSetter, "GothSwap: FORBIDDEN");
feeTo = _feeTo;
}
function setMigrator(address _migrator) external override {
require(msg.sender == feeToSetter, "GothSwap: FORBIDDEN");
migrator = _migrator;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, "GothSwap: FORBIDDEN");
feeToSetter = _feeToSetter;
}
}
// File contracts/swap/pairs/GothLibrary.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
library GothLibrary {
using SafeGothMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "GothLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "GothLibrary: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"ce6c6eec5cc8d69ac534e827be52dfa14275ce510e37a998b68561241626441b" // init code fuji
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IGothPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "GothLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "GothLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "GothLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "GothLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "GothLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File contracts/swap/pairs/IGothRouter.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IGothRouter {
function factory() external pure returns (address);
function WAVAX() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityAVAX(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountAVAX,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityAVAX(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountAVAX);
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 removeLiquidityAVAXWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountAVAX);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactAVAXForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactAVAX(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForAVAX(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapAVAXForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function removeLiquidityAVAXSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
) external returns (uint256 amountAVAX);
function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountAVAX);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactAVAXForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForAVAXSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// File contracts/swap/pairs/IWAVAX.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IWAVAX {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// File contracts/swap/pairs/GothRouter.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.6.12;
contract GothRouter is IGothRouter {
using SafeGothMath for uint256;
address public immutable override factory;
address public immutable override WAVAX;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "GothRouter: EXPIRED");
_;
}
constructor(address _factory, address _WAVAX) public {
factory = _factory;
WAVAX = _WAVAX;
}
receive() external payable {
assert(msg.sender == WAVAX); // only accept AVAX via fallback from the WAVAX contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
if (IGothFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IGothFactory(factory).createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) = GothLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = GothLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, "GothRouter: INSUFFICIENT_B_AMOUNT");
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = GothLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, "GothRouter: INSUFFICIENT_A_AMOUNT");
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = GothLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IGothPair(pair).mint(to);
}
function addLiquidityAVAX(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountAVAX,
uint256 liquidity
)
{
(amountToken, amountAVAX) = _addLiquidity(
token,
WAVAX,
amountTokenDesired,
msg.value,
amountTokenMin,
amountAVAXMin
);
address pair = GothLibrary.pairFor(factory, token, WAVAX);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWAVAX(WAVAX).deposit{value: amountAVAX}();
assert(IWAVAX(WAVAX).transfer(pair, amountAVAX));
liquidity = IGothPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountAVAX) TransferHelper.safeTransferAVAX(msg.sender, msg.value - amountAVAX);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) {
address pair = GothLibrary.pairFor(factory, tokenA, tokenB);
IGothPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = IGothPair(pair).burn(to);
(address token0, ) = GothLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, "GothRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "GothRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityAVAX(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountAVAX) {
(amountToken, amountAVAX) = removeLiquidity(
token,
WAVAX,
liquidity,
amountTokenMin,
amountAVAXMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWAVAX(WAVAX).withdraw(amountAVAX);
TransferHelper.safeTransferAVAX(to, amountAVAX);
}
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 virtual override returns (uint256 amountA, uint256 amountB) {
address pair = GothLibrary.pairFor(factory, tokenA, tokenB);
uint256 value = approveMax ? uint256(-1) : liquidity;
IGothPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityAVAXWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountToken, uint256 amountAVAX) {
address pair = GothLibrary.pairFor(factory, token, WAVAX);
uint256 value = approveMax ? uint256(-1) : liquidity;
IGothPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountAVAX) = removeLiquidityAVAX(token, liquidity, amountTokenMin, amountAVAXMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityAVAXSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountAVAX) {
(, amountAVAX) = removeLiquidity(
token,
WAVAX,
liquidity,
amountTokenMin,
amountAVAXMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IGothPairERC20(token).balanceOf(address(this)));
IWAVAX(WAVAX).withdraw(amountAVAX);
TransferHelper.safeTransferAVAX(to, amountAVAX);
}
function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountAVAXMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountAVAX) {
address pair = GothLibrary.pairFor(factory, token, WAVAX);
uint256 value = approveMax ? uint256(-1) : liquidity;
IGothPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountAVAX = removeLiquidityAVAXSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountAVAXMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = GothLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? GothLibrary.pairFor(factory, output, path[i + 2]) : _to;
IGothPair(GothLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = GothLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, "GothRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
amounts = GothLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "GothRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapExactAVAXForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WAVAX, "GothRouter: INVALID_PATH");
amounts = GothLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, "GothRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWAVAX(WAVAX).deposit{value: amounts[0]}();
assert(IWAVAX(WAVAX).transfer(GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactAVAX(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WAVAX, "GothRouter: INVALID_PATH");
amounts = GothLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, "GothRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
IWAVAX(WAVAX).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferAVAX(to, amounts[amounts.length - 1]);
}
function swapExactTokensForAVAX(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[path.length - 1] == WAVAX, "GothRouter: INVALID_PATH");
amounts = GothLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, "GothRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
IWAVAX(WAVAX).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferAVAX(to, amounts[amounts.length - 1]);
}
function swapAVAXForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) {
require(path[0] == WAVAX, "GothRouter: INVALID_PATH");
amounts = GothLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, "GothRouter: EXCESSIVE_INPUT_AMOUNT");
IWAVAX(WAVAX).deposit{value: amounts[0]}();
assert(IWAVAX(WAVAX).transfer(GothLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferAVAX(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = GothLibrary.sortTokens(input, output);
IGothPair pair = IGothPair(GothLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IGothPairERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = GothLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2 ? GothLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amountIn);
uint256 balanceBefore = IGothPairERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IGothPairERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"GothRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactAVAXForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
require(path[0] == WAVAX, "GothRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWAVAX(WAVAX).deposit{value: amountIn}();
assert(IWAVAX(WAVAX).transfer(GothLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint256 balanceBefore = IGothPairERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IGothPairERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
"GothRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForAVAXSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WAVAX, "GothRouter: INVALID_PATH");
TransferHelper.safeTransferFrom(path[0], msg.sender, GothLibrary.pairFor(factory, path[0], path[1]), amountIn);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IGothPairERC20(WAVAX).balanceOf(address(this));
require(amountOut >= amountOutMin, "GothRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWAVAX(WAVAX).withdraw(amountOut);
TransferHelper.safeTransferAVAX(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return GothLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountOut) {
return GothLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountIn) {
return GothLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return GothLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return GothLibrary.getAmountsIn(factory, amountOut, path);
}
}
// File contracts/swap/WAVAX.sol
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Contract name, token name, and token symbol modified by Ava Labs 2020
pragma solidity >=0.4.22 <0.6;
contract WAVAX {
string public name = "Wrapped AVAX";
string public symbol = "WAVAX";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
|
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
|
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "GothLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
| 12,842,402
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "hardhat/console.sol";
contract Vault {
using SafeERC20 for IERC20;
mapping (address => mapping (address => uint256)) public deposits;
// 编写deposit ⽅法,实现 ERC20 存⼊ Vault,并记录每个⽤户存款⾦额
function deposit(address _token, uint256 _amount) public {
// 存款⾦额记录
//(bool success, bytes memory data) = _token.delegatecall(abi.encodeWithSignature("approve(address, uint256)", address(this), _amount));
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
deposits[_token][msg.sender] += _amount;
}
function withdraw(address _token, uint _amount) public {
// 提取⾦额记录
require(deposits[_token][msg.sender] >= _amount, "not enough balance");
IERC20(_token).safeTransfer(msg.sender, _amount);
deposits[_token][msg.sender] -= _amount;
}
}
|
存款⾦额记录(bool success, bytes memory data) = _token.delegatecall(abi.encodeWithSignature("approve(address, uint256)", address(this), _amount));
|
function deposit(address _token, uint256 _amount) public {
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
deposits[_token][msg.sender] += _amount;
}
| 984,337
|
./full_match/5/0xd507cebBd76bFA8ef39562282a2c8EdD4Fc68D77/sources/project_/contracts/BaseContracts/Standards/ERC721A.sol
|
To change the starting tokenId, please override this function./
|
function _startTokenId() internal pure virtual returns (uint256) {
return 0;
}
| 1,901,255
|
/* SPDX-License-Identifier: MIT
Please go trough the Readme file.
*/
pragma solidity 0.8.10;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
contract NFTContract is OwnableUpgradeable, ERC721EnumerableUpgradeable{
using StringsUpgradeable for uint256;
address public devs;
uint256 public cost;
uint public maxSupply;
uint whitelistLock;
uint preSaleEnd;
bool collectionIsReavealed;
uint launchBlock;
bool isRevealed;
string public unRevealedURI;
string public collection;
/**
whitelist to be use once with no more than 500 addresses
*/
address[] public whitelist;
/*
Fees per Nft.
nftId => asset => amount
this ways fees can be paid in any assets
*/
// only one nft per account
mapping(address => bool) public mintedPresale;
mapping(address => uint) public minted;
mapping(uint => string) private botUri;
function initialize(
address devs_,
uint256 price_,
uint256 maxSupply_,
uint launchBlock_,
uint presaleLen_,
uint devsQty,
string memory name_,
string memory symbol_,
string memory unRevealedUri_,
string memory collectionData_
)public initializer {
__ERC721_init(name_, symbol_);
__Ownable_init();
devs = devs_;
cost = price_;
maxSupply = maxSupply_;
launchBlock = launchBlock_;
preSaleEnd = launchBlock + presaleLen_;
unRevealedURI = unRevealedUri_;
collection = collectionData_;
mintDevsNft(devsQty);
}
function mint(uint256 _qty, address _to) external payable {
require(totalSupply() < maxSupply,"Sold Out");
require(_qty <= 5,"5 MAX");
require(maxSupply >= totalSupply()+_qty, "Not enough left");
require(block.number > launchBlock,"To soon!");
uint256 yourPrice;
if( block.number < preSaleEnd ){
require(!mintedPresale[msg.sender],"Already minted presale");
require(isWhitelist(msg.sender),"Must be white listed");
require(_qty == 1,"Only one in presale");
yourPrice = cost/4*3 + _qty;
mintedPresale[msg.sender] = true;
}
else{
require(minted[msg.sender] < 5,"Maximum reached");
yourPrice = cost * _qty;
minted[msg.sender] +=_qty;
}
require(msg.value == yourPrice,"Price not right");
payDevs();
for(uint i = 0 ; i<_qty;i++){
_safeMint(_to, totalSupply()+1);
}
}
///@notice Fill the whitelist with no more than 500 address
///@dev to call once only. will lock after
function fillWhitelist(address[] memory accounts) external onlyOwner{
require(whitelist.length <= 500,"To many whitelisted");
whitelistLock =1;
whitelist = accounts;
}
///@notice check if an account is whitelisted.
///@dev if we dont want contract to mint we should use tx.origin
function isWhitelist(address _account) public view returns(bool isWhiteListed) {
for(uint256 i = 0; i < whitelist.length;i++){
if(_account == whitelist[i]){
return true;
}
}
return false;
}
///@notice Fill the whitelist with no more than 500 address
///@param _uri ipfs foolder hash
///@dev to call once only. will lock after
function reveal(string memory _uri) external onlyOwner{
unRevealedURI = _uri;
}
/// @notice Return the token uri that was randomly atributed to that toke id
/// @param _id the token id
function tokenURI(uint256 _id) public view virtual override returns (string memory) {
return string(abi.encodePacked('https://ipfs.io/ipfs/', unRevealedURI,'/', _id.toString(),'.json'));
}
/// @notice For Opensea Royalties
function contractURI() public view returns (string memory) {
return string(abi.encodePacked('https://ipfs.io/ipfs/', collection ));
}
function updateURI(string memory _ipfshash) external onlyOwner{
collection = string(abi.encodePacked(_ipfshash));
}
/// @notice For Opensea Royalties
/// @param _qty the quantity to mint
/// @dev called upon deployment to resrve _qty
function mintDevsNft(uint256 _qty) internal {
for(uint i =0; i<_qty; i++){
_safeMint(devs,totalSupply()+1);
}
minted[devs] = _qty;
}
/// @notice For Opensea Royalties
/// @dev called upon deployment to resrve _qty
function payDevs() internal {
(bool success, ) = payable(devs).call{
value: address(this).balance
}("");
require(success);
}
receive() external payable{
// allow contract to receive ETH
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Initializes the contract by setting a `name` and a `symbol` to the token collection./
|
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
| 205,293
|
./full_match/80001/0x2c5A1fc0187c1A1B1931b563aC9a08e21833DA91/sources/contracts/Mining.sol
|
Ensure the player has at least 1 of the token they are trying to stake If they have a pickaxe already, send it back to them. Transfer using safeTransfer
|
function stake(uint256 _tokenId) external nonReentrant {
require(
pickaxeNftCollection.balanceOf(msg.sender, _tokenId) >= 1,
"You must have at least 1 of the item you are trying to stake"
);
if (playerPickaxe[msg.sender].isData) {
pickaxeNftCollection.safeTransferFrom(
address(this),
msg.sender,
playerPickaxe[msg.sender].value,
1,
"Returning your old item"
);
}
rewardsToken.transfer(msg.sender, reward);
msg.sender,
address(this),
_tokenId,
1,
"Staking your pickaxe"
);
playerPickaxe[msg.sender].isData = true;
playerLastUpdate[msg.sender].value = block.timestamp;
rewards[msg.sender]=0;
}
| 841,627
|
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.10;
/**
* @title MockL2OutputOracle
*/
contract MockL2OutputOracle {
uint256 public submissionFrequency;
uint256 public l2BlockTime;
mapping(uint256 => bytes32) public l2Outputs;
uint256 public historicalTotalBlocks;
uint256 public latestBlockTimestamp;
uint256 public startingBlockTimestamp;
/**
* Initialize the MockL2OutputOracle contract.
* @param _submissionFrequency The desired interval in seconds at which
* checkpoints must be submitted.
* @param _l2BlockTime The desired L2 inter-block time in seconds.
* @param _genesisL2Output The initial L2 output of the L2 chain.
* @param _historicalTotalBlocks The number of blocks that preceding the
* initialization of the L2 chain.
*/
constructor(
uint256 _submissionFrequency,
uint256 _l2BlockTime,
bytes32 _genesisL2Output,
uint256 _historicalTotalBlocks
) {
submissionFrequency = _submissionFrequency;
l2BlockTime = _l2BlockTime;
l2Outputs[block.timestamp] = _genesisL2Output; // solhint-disable not-rely-on-time
historicalTotalBlocks = _historicalTotalBlocks;
latestBlockTimestamp = block.timestamp; // solhint-disable not-rely-on-time
startingBlockTimestamp = block.timestamp; // solhint-disable not-rely-on-time
}
/**
* Accepts an L2 output checkpoint and the timestamp of the corresponding L2
* block. The timestamp must be equal to the current value returned by
* `nextTimestamp()` in order to be accepted.
* @param _l2Output The L2 output of the checkpoint block.
* @param _timestamp The L2 block timestamp that resulted in _l2Output.
*/
function appendL2Output(bytes32 _l2Output, uint256 _timestamp) external {
require(block.timestamp > _timestamp, "Cannot append L2 output in future");
require(_l2Output != bytes32(0), "Cannot submit empty L2 output");
require(_timestamp == nextTimestamp(), "Timestamp not equal to next expected timestamp");
l2Outputs[_timestamp] = _l2Output;
latestBlockTimestamp = _timestamp;
}
/**
* Computes the timestamp of the next L2 block that needs to be
* checkpointed.
*/
function nextTimestamp() public view returns (uint256) {
return latestBlockTimestamp + submissionFrequency;
}
/**
* Computes the L2 block number given a target L2 block timestamp.
* @param _timestamp The L2 block timestamp of the target block.
*/
function computeL2BlockNumber(uint256 _timestamp) external view returns (uint256) {
require(_timestamp >= startingBlockTimestamp, "timestamp prior to startingBlockTimestamp");
return historicalTotalBlocks + (_timestamp - startingBlockTimestamp) / l2BlockTime;
}
}
|
Computes the timestamp of the next L2 block that needs to be checkpointed./
|
function nextTimestamp() public view returns (uint256) {
return latestBlockTimestamp + submissionFrequency;
}
| 12,811,218
|
./partial_match/1/0x1fB359D35c209399F47b4C1a040bD49b24Ae90be/sources/AutobahnToken.sol
|
------------------------------------------------------------------------ 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);
}
event Burn(address indexed burner, uint256 value);
| 3,911,890
|
// SPDX-License-Identifier: MIT
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
////import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
////import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
////import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [////IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* ////IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
////import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "@openzeppelin/contracts/access/Ownable.sol";
////import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @title Divinity Cell DivinityCellWhitelist Contract
* @notice Part of the DivinityCellMinter
* @author Apriorit
*/
contract DivinityCellWhitelist is Ownable {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet _whitelisted_users;
/**
* @notice Add toWhitelist address to the whitelist
* @param toWhitelist The address of account to whitelist
* @return Whether or not the transaction succeeded
*/
function whitelist(address toWhitelist) external onlyOwner returns(bool) {
require(!_whitelisted_users.contains(toWhitelist), "Address is already in whitelist");
_whitelisted_users.add(toWhitelist);
return true;
}
function getWhitelist() external view returns(address[] memory) {
return _whitelisted_users.values();
}
/**
* @notice Remove toUnWhitelist address from whitelist
* @param toUnWhitelist The address of account to remove from whitelist
* @return Whether or not the transaction succeeded
*/
function unwhitelist(address toUnWhitelist) external onlyOwner returns(bool) {
require(_whitelisted_users.contains(toUnWhitelist), "Address is not in whitelist");
_whitelisted_users.remove(toUnWhitelist);
return true;
}
/**
* @notice Add toWhitelist list of addresses into whitelist
* @param toWhitelist The addresses of accounts to add to the whitelist
* @return Whether or not the transaction succeeded
*/
function whitelistMany(address[] memory toWhitelist) external onlyOwner returns(bool) {
for (uint i = 0; i < toWhitelist.length; i++) {
_whitelisted_users.add(toWhitelist[i]);
}
return true;
}
/**
* @notice Remove toUnWhitelist list of addresses from the whitelist
* @param toUnWhitelist The addresses of accounts to remove from the whitelist
* @return Whether or not the transaction succeeded
*/
function unwhitelistMany(address[] memory toUnWhitelist) external onlyOwner returns(bool) {
for (uint i = 0; i < toUnWhitelist.length; i++) {
_whitelisted_users.remove(toUnWhitelist[i]);
}
return true;
}
/**
* @notice Check if account whitelisted or not
* @param account Account that we want to check
* @return Whether or not the account in the whitelist
*/
function is_whitelisted(address account) public view returns(bool) {
return _whitelisted_users.contains(account);
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
////import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
////import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
////import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
////import "@openzeppelin/contracts/utils/Address.sol";
////import "@openzeppelin/contracts/utils/Context.sol";
////import "@openzeppelin/contracts/utils/Strings.sol";
////import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
event Premint(address indexed _to, uint256 indexed start_id, uint256 indexed count);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
function _mint_many(address to, uint256 first_tokenId, uint256 count) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(first_tokenId), "ERC721: token already minted");
uint256 last_id = first_tokenId + count;
for (uint256 i = first_tokenId; i < last_id; i++) {
_mint(to, i);
}
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "@openzeppelin/contracts/utils/math/SafeMath.sol";
////import "@openzeppelin/contracts/utils/Counters.sol";
////import "./utility/ERC721.sol";
////import "./DivinityCellWhitelist.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title Divinity Cell DivinityCellNFT Contract
* @author Apriorit
*/
contract DivinityCellNFT is ERC721, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
string base_url;
address burner;
address _minter;
address proxyRegistryAddress;
Counters.Counter _nextTokenId;
/**
* @notice Ensures that sender has burn rights
*/
modifier onlyBurner {
require(msg.sender == burner, "DivinityCellNFT: Sender must have burner role");
_;
}
/**
* @notice Ensures that sender has mint rights
*/
modifier onlyMinter {
require(msg.sender == _minter, "DivinityCellNFT: Sender is not auction");
_;
}
/**
* @param _name Token name
* @param _symbol Token syumbol
* @param token_url Token base URI
* @param _proxyRegistryAddress OpenSea existring proxy registry. On Mainnet it is 0xa5409ec958c83c3f309868babaca7c86dcb077c1
*/
constructor(
string memory _name,
string memory _symbol,
string memory token_url,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
base_url = token_url;
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* @notice Check if account is owner of tokenId
* @param account The address of account that we want to check
* @param tokenId ID that we are checking
* @return Whether or not the account is owner of tokenId
*/
function isTokenOwner(uint256 tokenId, address account) external view returns(bool) {
return ERC721.ownerOf(tokenId) == account;
}
/**
* @notice Mint token for recipient. Can be called only by _minter
* @param recipient The address of account that will recieve token
* @return Minted token ID
*/
function mintTo(address recipient) external onlyMinter returns(uint256) {
uint256 currentTokenId = _nextTokenId.current();
_nextTokenId.increment();
_safeMint(recipient, currentTokenId);
return currentTokenId;
}
/**
* @notice Mint count tokens for account. Can be called only by contract owner
* @param account The address of account that will recieve tokens
* @param count Count of tokens to mint
* @return Whether or not the transaction succeeded
*/
function premint(address account, uint256 count) external onlyMinter returns(bool) {
uint256 currentTokenId = _nextTokenId.current();
ERC721._mint_many(account, currentTokenId, count);
_nextTokenId._value += count;
return true;
}
/**
* @notice Set new _minter. Only owner can call this. Can be called only by contract owner
* @param minter The address of new minter
* @return Whether or not the transaction succeeded
*/
function registerMinterContract(address minter) external onlyOwner returns(bool){
_minter = minter;
return true;
}
/**
* @notice Get current last token ID + 1.(total amount)
* @return Current amount of tokens
*/
function totalSupply() external view returns (uint256) {
return _nextTokenId.current();
}
/**
* @notice Set new token URI. Can be called only by contract owner
* @param baseUrl New token URL
* @return Whether or not the transaction succeeded
*/
function setURI(string memory baseUrl) external onlyOwner returns (bool) {
base_url = baseUrl;
return true;
}
/**
* @notice Get token URI
* @return Current token URI
*/
function URI() public view returns (string memory) {
return base_url;
}
/**
* @notice Get _tokenId URI
* @param _tokenId Token for which we want to get URI
* @return Token URI
*/
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(URI(), Strings.toString(_tokenId)));
}
/**
* @notice Set new token burner. Can be called only by contract owner
* @param newBurner New burner account
* @return Whether or not the transaction succeeded
*/
function setBurner(address newBurner) external onlyOwner returns(bool) {
burner = newBurner;
return true;
}
/**
* @notice Set new token burner. Can be called only by contract burner
* @param tokenId Token to be burned
* @return Whether or not the transaction succeeded
*/
function burn(uint256 tokenId) external onlyBurner returns(bool) {
_burn(tokenId);
return true;
}
/**
* @notice Checks if token with given id exists
* @param tokenId Checked token
* @return Whether or not the token exists
*/
function exists(uint256 tokenId) external view returns(bool) {
return ERC721._exists(tokenId);
}
/**
* @notice Checks if operator can perform actions for owner
* @param owner Tokens owner
* @param operator Account that want perform actions for owner
* @return Whether or not the transaction succeeded
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
////import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* SourceUnit: g:\Projects\blockchain\divinitycels\DC-contracts\contracts\DivinityCellMinter.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "@openzeppelin/contracts/access/Ownable.sol";
////import "@openzeppelin/contracts/security/Pausable.sol";
////import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
////import "@openzeppelin/contracts/utils/math/SafeMath.sol";
////import "@openzeppelin/contracts/utils/math/Math.sol";
////import "./DivinityCellNFT.sol";
/**
* @title Divinity Cell DivinityCellMinter Contract
* @notice Used for token presales
* @author Apriorit
*/
contract DivinityCellMinter is ReentrancyGuard, Ownable, Pausable, DivinityCellWhitelist {
using SafeMath for uint256;
uint256 public tokens_limit;
uint256 public tokens_this_sale = 0;
uint32 public buy_limit;
uint32 current_sale_id = 0;
uint256 public mint_price;
uint256 public sale_end_timestamp = 0;
uint256 public sale_start_timestamp = 0;
bool public is_sell_private = true;
mapping(uint => mapping(address => uint)) bought_current_sell;
address nft_contract;
address whitelist_contract;
/**
* @notice Return bought count for the current sale
* @param account Account that we want to check
* @return Count of bought tokens for the current sale
*/
function boughtCurrentSale(address account) public view returns(uint) {
return bought_current_sell[current_sale_id][account];
}
/**
* @notice If current sale is private, ensures that it still continues and sender is whitelisted
*/
modifier minterAllowed {
if (is_sell_private) {
require(block.timestamp < sale_end_timestamp, "DivinityCellAuction: Sale ended");
if (mint_price == 0) {
require(DivinityCellWhitelist(whitelist_contract).is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted");
} else {
require(is_whitelisted(msg.sender), "DivinityCellAuction: Account is not whitelisted");
}
}
_;
}
/**
* @notice Ensures that there is no other sale. If last sale was public, ensures that all tokens sold
*/
modifier onlyIfNoSale {
require(sale_start_timestamp < block.timestamp, "DivinityCellAuction: New sale is about to start");
if (tokens_this_sale != 0) {
require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale still continues");
}
_;
}
/**
* @notice Sets new mint price for token mint. Can be called only by contract owner
* @param nft address of NFT tokens contract, used for minting
* @param nft address of whitelist contract, used for free minting
* @param tokens_count Amount of tokens to be minted
* @param initial_mint_price Initial minting price
*/
constructor(address nft, address whitelist, uint32 tokens_count, uint256 initial_mint_price) {
tokens_limit = tokens_count;
nft_contract = nft;
whitelist_contract = whitelist;
mint_price = initial_mint_price;
}
/**
* @notice Send all eth collected by contract to _to account. Can be called only by contract owner
* @param _to The account that will receive contract ETH
* @return Whether or not the transaction succeeded
*/
function collectETH(address payable _to) external onlyOwner payable returns(bool) {
(bool sent,) = _to.call{value: address(this).balance}("");
require(sent, "DivinityCellAuction: Failed to send Ether");
return true;
}
/**
* @notice Sets new mint price for token mint. Can be called only by contract owner
* @param new_mint_price New mint price
* @return Whether or not the transaction succeeded
*/
function setPrice(uint256 new_mint_price) external onlyOwner returns(bool) {
mint_price = new_mint_price;
return true;
}
/**
* @notice Starts private token sale. Can be called only by contract owner and only if other sale is not running
* @param per_user_limitation Number of tokens that be bought by accounts this sale
* @param tokens_count Number of tokens that will be sold this sale
* @param new_sale_end_timestamp Sale start timestamp
* @param new_sale_start_timestamp Sale end timestamp
* @return Whether or not the transaction succeeded
*/
function startPrivateSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner onlyIfNoSale returns(bool) {
require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens");
require(new_sale_end_timestamp > block.timestamp, "DivinityCellAuction: Wrong timestamp passed");
require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date");
require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed");
require(tokens_count > 0, "DivinityCellAuction: Wrong token count passed");
tokens_this_sale = tokens_count;
buy_limit = per_user_limitation;
sale_end_timestamp = new_sale_end_timestamp;
sale_start_timestamp = new_sale_start_timestamp;
current_sale_id += 1;
is_sell_private = true;
return true;
}
/**
* @notice Changes sale start and end timestamps.
* @param new_sale_end_timestamp New sale start timestamp
* @param new_sale_start_timestamp New sale end timestamp
* @return Whether or not the transaction succeeded
*/
function reschedulePrivateSale(uint256 new_sale_start_timestamp, uint256 new_sale_end_timestamp) external onlyOwner returns(bool) {
require(new_sale_start_timestamp < new_sale_end_timestamp, "DivinityCellAuction: Start date should be less than end date");
require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left");
sale_end_timestamp = new_sale_end_timestamp;
sale_start_timestamp = new_sale_start_timestamp;
return true;
}
/**
* @notice Starts public token sale. Can be called only by contract owner and only if other sale is not running.
* Unlike private one, this will end only after all tokens are bought
* @param per_user_limitation Number of tokens that be bought by accounts this sale
* @param new_sale_start_timestamp Sale start timestamp
* @return Whether or not the transaction succeeded
*/
function startPublicSale(uint32 per_user_limitation, uint256 tokens_count, uint256 new_sale_start_timestamp) external onlyOwner onlyIfNoSale returns(bool) {
require(tokens_limit >= tokens_count, "DivinityCellAuction: Cant sell that much tokens");
require(tokens_limit > 0, "DivinityCellAuction: Cant sell that much tokens");
require(per_user_limitation > 0, "DivinityCellAuction: Wrong limitation passed");
tokens_this_sale = tokens_count;
sale_start_timestamp = new_sale_start_timestamp;
buy_limit = per_user_limitation;
current_sale_id += 1;
is_sell_private = false;
return true;
}
/**
* @notice Changes sale start timestamp.
* @param new_sale_start_timestamp New start end timestamp
* @return Whether or not the transaction succeeded
*/
function reschedulePublicSale(uint256 new_sale_start_timestamp) external onlyOwner returns(bool) {
require(sale_end_timestamp < block.timestamp, "DivinityCellAuction: Private sale continues");
require(tokens_this_sale > 0, "DivinityCellAuction: No tokens left");
sale_start_timestamp = new_sale_start_timestamp;
return true;
}
/**
* @notice pause current sale. Emits pause event
*/
function pause() public onlyOwner {
Pausable._pause();
}
/**
* @notice unpause current sale. Emits unpause event
*/
function unpause() public onlyOwner {
Pausable._unpause();
}
/**
* @notice Mints token for transaction sender. Can't be called if sale is not started
* @return ID of minted token
*/
function mint(uint256 amount) public payable whenNotPaused minterAllowed nonReentrant returns(bool) {
uint256 userLimit = getMintLimit();
require(userLimit > 0, "DivinityCellAuction: This recipient cant buy more tokens this sale");
require(amount > 0, "DivinityCellAuction: Invalid amount");
require(block.timestamp >= sale_start_timestamp, "DivinityCellAuction: Sale hasn't started yet");
uint256 count = Math.min(amount, userLimit);
require(msg.value == mint_price * count, "DivinityCellAuction: Wrong amount of eth sent");
require(tokens_this_sale >= count, "DivinityCellAuction: Nothing to sell");
require(tokens_limit >= count, "DivinityCellAuction: Nothing to sell");
bool isMinted = DivinityCellNFT(nft_contract).premint(msg.sender, count);
require(isMinted, "DivinityCellAuction: mint failed");
bought_current_sell[current_sale_id][msg.sender] += count;
tokens_this_sale -= count;
tokens_limit -= count;
return isMinted;
}
/**
* @notice Mint count tokens for account. Can be called only by contract owner
* @param account The address of account that will recieve tokens
* @param count Count of tokens to mint
* @return Whether or not the transaction succeeded
*/
function premint(address account, uint256 count) external onlyOwner nonReentrant returns(bool) {
require(tokens_limit >= count, "DivinityCellAuction: can't mint that much tokens");
bool is_premnt_successful = DivinityCellNFT(nft_contract).premint(account, count);
require(is_premnt_successful, "DivinityCellAuction: premint was unsuccessful");
tokens_limit -= count;
return is_premnt_successful;
}
// Helpers
/**
* @return amount of tokens available for current mint transaction
*/
function getMintLimit() internal view returns(uint) {
if (is_sell_private) {
uint bought = boughtCurrentSale(msg.sender);
if (mint_price == 0) {
if (bought > 0) {
return 0;
}
uint256 holdings = DivinityCellNFT(nft_contract).balanceOf(msg.sender);
if (holdings >= 5) {
return 2;
}
if (holdings >= 3) {
return 1;
}
return 0;
}
return buy_limit - bought;
}
return 5;
}
}
|
Check if account whitelisted or not account Account that we want to check return Whether or not the account in the whitelist/
|
function is_whitelisted(address account) public view returns(bool) {
return _whitelisted_users.contains(account);
}
| 76,697
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../libraries/SafeMath.sol";
import "../libraries/SafeERC20.sol";
import "../interfaces/IERC20.sol";
import "./interfaces/IHermesERC20.sol";
import "./interfaces/IHermesPair.sol";
import "./interfaces/IHermesFactory.sol";
import "../boringcrypto/BoringOwnable.sol";
interface IMasterChef {
struct PoolInfo {
IHermesERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HERMES to distribute per block.
uint256 lastRewardTimestamp; // Last block number that HERMES distribution occurs.
uint256 accHermesPerShare; // Accumulated HERMES per share, times 1e12. See below.
}
function poolLength() external view returns (uint256);
function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory);
function totalAllocPoint() external view returns (uint256);
function hermesPerSec() external view returns (uint256);
}
contract FarmLens is BoringOwnable {
using SafeMath for uint256;
address public hermes; // 0x6e84a6216eA6dACC71eE8E6b0a5B7322EEbC0fDd;
address public wone; // 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7;
address public woneUsdt; // 0xeD8CBD9F0cE3C6986b22002F03c6475CEb7a6256
address public woneUsdc; // 0x87Dee1cC9FFd464B79e058ba20387c1984aed86a
address public woneDai; // 0xA389f9430876455C36478DeEa9769B7Ca4E3DDB1
IHermesFactory public hermesFactory; // IHermesFactory(0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10);
IMasterChef public chefv2; //0xd6a4F121CA35509aF06A0Be99093d08462f53052
IMasterChef public chefv3; //0x188bED1968b795d5c9022F6a0bb5931Ac4c18F00
constructor(
address hermes_,
address wone_,
address woneUsdt_,
address woneUsdc_,
address woneDai_,
IHermesFactory hermesFactory_,
IMasterChef chefv2_,
IMasterChef chefv3_
) public {
hermes = hermes_;
wone = wone_;
woneUsdt = woneUsdt_;
woneUsdc = woneUsdc_;
woneDai = woneDai_;
hermesFactory = IHermesFactory(hermesFactory_);
chefv2 = chefv2_;
chefv3 = chefv3_;
}
/// @notice Returns price of one in usd.
function getAvaxPrice() public view returns (uint256) {
uint256 priceFromWoneUsdt = _getAvaxPrice(IHermesPair(woneUsdt)); // 18
uint256 priceFromWoneUsdc = _getAvaxPrice(IHermesPair(woneUsdc)); // 18
uint256 priceFromWoneDai = _getAvaxPrice(IHermesPair(woneDai)); // 18
uint256 sumPrice = priceFromWoneUsdt.add(priceFromWoneUsdc).add(priceFromWoneDai); // 18
uint256 onePrice = sumPrice / 3; // 18
return onePrice; // 18
}
/// @notice Returns value of wone in units of stablecoins per wone.
/// @param pair A wone-stablecoin pair.
function _getAvaxPrice(IHermesPair pair) private view returns (uint256) {
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
if (pair.token0() == wone) {
reserve1 = reserve1.mul(_tokenDecimalsMultiplier(pair.token1())); // 18
return (reserve1.mul(1e18)) / reserve0; // 18
} else {
reserve0 = reserve0.mul(_tokenDecimalsMultiplier(pair.token0())); // 18
return (reserve0.mul(1e18)) / reserve1; // 18
}
}
/// @notice Get the price of a token in Usd.
/// @param tokenAddress Address of the token.
function getPriceInUsd(address tokenAddress) public view returns (uint256) {
return (getAvaxPrice().mul(getPriceInAvax(tokenAddress))) / 1e18; // 18
}
/// @notice Get the price of a token in Avax.
/// @param tokenAddress Address of the token.
/// @dev Need to be aware of decimals here, not always 18, it depends on the token.
function getPriceInAvax(address tokenAddress) public view returns (uint256) {
if (tokenAddress == wone) {
return 1e18;
}
IHermesPair pair = IHermesPair(hermesFactory.getPair(tokenAddress, wone));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
address token0Address = pair.token0();
address token1Address = pair.token1();
if (token0Address == wone) {
reserve1 = reserve1.mul(_tokenDecimalsMultiplier(token1Address)); // 18
return (reserve0.mul(1e18)) / reserve1; // 18
} else {
reserve0 = reserve0.mul(_tokenDecimalsMultiplier(token0Address)); // 18
return (reserve1.mul(1e18)) / reserve0; // 18
}
}
/// @notice Calculates the multiplier needed to scale a token's numerical field to 18 decimals.
/// @param tokenAddress Address of the token.
function _tokenDecimalsMultiplier(address tokenAddress) private pure returns (uint256) {
uint256 decimalsNeeded = 18 - IHermesERC20(tokenAddress).decimals();
return 1 * (10**decimalsNeeded);
}
/// @notice Calculates the reserve of a pair in usd.
/// @param pair Pair for which the reserve will be calculated.
function getReserveUsd(IHermesPair pair) public view returns (uint256) {
address token0Address = pair.token0();
address token1Address = pair.token1();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
reserve0 = reserve0.mul(_tokenDecimalsMultiplier(token0Address)); // 18
reserve1 = reserve1.mul(_tokenDecimalsMultiplier(token1Address)); // 18
uint256 token0PriceInAvax = getPriceInAvax(token0Address); // 18
uint256 token1PriceInAvax = getPriceInAvax(token1Address); // 18
uint256 reserve0Avax = reserve0.mul(token0PriceInAvax); // 36;
uint256 reserve1Avax = reserve1.mul(token1PriceInAvax); // 36;
uint256 reserveAvax = (reserve0Avax.add(reserve1Avax)) / 1e18; // 18
uint256 reserveUsd = (reserveAvax.mul(getAvaxPrice())) / 1e18; // 18
return reserveUsd; // 18
}
struct FarmPair {
uint256 id;
uint256 allocPoint;
address lpAddress;
address token0Address;
address token1Address;
string token0Symbol;
string token1Symbol;
uint256 reserveUsd;
uint256 totalSupplyScaled;
address chefAddress;
uint256 chefBalanceScaled;
uint256 chefTotalAlloc;
uint256 chefHermesPerSec;
}
/// @notice Gets the farm pair data for a given MasterChef.
/// @param chefAddress The address of the MasterChef.
/// @param whitelistedPids Array of all ids of pools that are whitelisted and valid to have their farm data returned.
function getFarmPairs(address chefAddress, uint256[] calldata whitelistedPids)
public
view
returns (FarmPair[] memory)
{
IMasterChef chef = IMasterChef(chefAddress);
uint256 whitelistLength = whitelistedPids.length;
FarmPair[] memory farmPairs = new FarmPair[](whitelistLength);
for (uint256 i = 0; i < whitelistLength; i++) {
IMasterChef.PoolInfo memory pool = chef.poolInfo(whitelistedPids[i]);
IHermesPair lpToken = IHermesPair(address(pool.lpToken));
//get pool information
farmPairs[i].id = whitelistedPids[i];
farmPairs[i].allocPoint = pool.allocPoint;
// get pair information
address lpAddress = address(lpToken);
address token0Address = lpToken.token0();
address token1Address = lpToken.token1();
farmPairs[i].lpAddress = lpAddress;
farmPairs[i].token0Address = token0Address;
farmPairs[i].token1Address = token1Address;
farmPairs[i].token0Symbol = IHermesERC20(token0Address).symbol();
farmPairs[i].token1Symbol = IHermesERC20(token1Address).symbol();
// calculate reserveUsd of lp
farmPairs[i].reserveUsd = getReserveUsd(lpToken); // 18
// calculate total supply of lp
farmPairs[i].totalSupplyScaled = lpToken.totalSupply().mul(_tokenDecimalsMultiplier(lpAddress));
// get masterChef data
uint256 balance = lpToken.balanceOf(chefAddress);
farmPairs[i].chefBalanceScaled = balance.mul(_tokenDecimalsMultiplier(lpAddress));
farmPairs[i].chefAddress = chefAddress;
farmPairs[i].chefTotalAlloc = chef.totalAllocPoint();
farmPairs[i].chefHermesPerSec = chef.hermesPerSec();
}
return farmPairs;
}
struct AllFarmData {
uint256 onePriceUsd;
uint256 hermesPriceUsd;
uint256 totalAllocChefV2;
uint256 totalAllocChefV3;
uint256 hermesPerSecChefV2;
uint256 hermesPerSecChefV3;
FarmPair[] farmPairsV2;
FarmPair[] farmPairsV3;
}
/// @notice Get all data needed for useFarms hook.
/// @param whitelistedPidsV2 Array of all ids of pools that are whitelisted in chefV2.
/// @param whitelistedPidsV3 Array of all ids of pools that are whitelisted in chefV3.
function getAllFarmData(uint256[] calldata whitelistedPidsV2, uint256[] calldata whitelistedPidsV3)
public
view
returns (AllFarmData memory)
{
AllFarmData memory allFarmData;
allFarmData.onePriceUsd = getAvaxPrice();
allFarmData.hermesPriceUsd = getPriceInUsd(hermes);
allFarmData.totalAllocChefV2 = IMasterChef(chefv2).totalAllocPoint();
allFarmData.hermesPerSecChefV2 = IMasterChef(chefv2).hermesPerSec();
allFarmData.totalAllocChefV3 = IMasterChef(chefv3).totalAllocPoint();
allFarmData.hermesPerSecChefV3 = IMasterChef(chefv3).hermesPerSec();
allFarmData.farmPairsV2 = getFarmPairs(address(chefv2), whitelistedPidsV2);
allFarmData.farmPairsV3 = getFarmPairs(address(chefv3), whitelistedPidsV3);
return allFarmData;
}
}
|
Get the price of a token in Usd. tokenAddress Address of the token.
|
function getPriceInUsd(address tokenAddress) public view returns (uint256) {
}
| 6,387,646
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "erc-payable-token/contracts/token/ERC1363/ERC1363.sol";
import "eth-token-recover/contracts/TokenRecover.sol";
import "./behaviours/ERC20Mintable.sol";
import "../../service/ServicePayer.sol";
/**
* @title AmazingERC20
* @dev Implementation of the AmazingERC20
*/
contract AmazingERC20 is
ERC20Mintable,
ERC20Burnable,
ERC1363,
TokenRecover,
ServicePayer
{
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 initialBalance,
address payable feeReceiver
) payable ERC1363(name, symbol) ServicePayer(feeReceiver, "AmazingERC20") {
_setupDecimals(decimals);
_mint(_msgSender(), initialBalance);
}
/**
* @dev Function to mint tokens.
*
* NOTE: restricting access to addresses with MINTER role. See {ERC20Mintable-mint}.
*
* @param account The address that will receive the minted tokens
* @param amount The amount of tokens to mint
*/
function _mint(address account, uint256 amount)
internal
override
onlyOwner
{
super._mint(account, amount);
}
/**
* @dev Function to stop minting new tokens.
*
* NOTE: restricting access to owner only. See {ERC20Mintable-finishMinting}.
*/
function _finishMinting() internal override onlyOwner {
super._finishMinting();
}
}
|
Function to mint tokens. NOTE: restricting access to addresses with MINTER role. See {ERC20Mintable-mint}. account The address that will receive the minted tokens amount The amount of tokens to mint/
|
function _mint(address account, uint256 amount)
internal
override
onlyOwner
{
super._mint(account, amount);
}
| 7,224,060
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.4;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {
AccessControlUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {Rescuable} from "../libs/Rescuable.sol";
// Interface for money market protocols (Compound, Aave, etc.)
abstract contract MoneyMarket is
Rescuable,
OwnableUpgradeable,
AccessControlUpgradeable
{
bytes32 internal constant RESCUER_ROLE = keccak256("RESCUER_ROLE");
function __MoneyMarket_init(address rescuer) internal initializer {
__Ownable_init();
__AccessControl_init();
// RESCUER_ROLE is managed by itself
_setupRole(RESCUER_ROLE, rescuer);
_setRoleAdmin(RESCUER_ROLE, RESCUER_ROLE);
}
function deposit(uint256 amount) external virtual;
function withdraw(uint256 amountInUnderlying)
external
virtual
returns (uint256 actualAmountWithdrawn);
/**
@notice The total value locked in the money market, in terms of the underlying stablecoin
*/
function totalValue() external returns (uint256) {
return _totalValue(_incomeIndex());
}
/**
@notice The total value locked in the money market, in terms of the underlying stablecoin
*/
function totalValue(uint256 currentIncomeIndex)
external
view
returns (uint256)
{
return _totalValue(currentIncomeIndex);
}
/**
@notice Used for calculating the interest generated (e.g. cDai's price for the Compound market)
*/
function incomeIndex() external returns (uint256 index) {
return _incomeIndex();
}
function stablecoin() external view virtual returns (ERC20);
function claimRewards() external virtual; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool
function setRewards(address newValue) external virtual;
/**
@dev IMPORTANT MUST READ
This function is for restricting unauthorized accounts from taking funds
and ensuring only tokens not used by the MoneyMarket can be rescued.
IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY
MAKE SURE YOU DO ALL OF THE FOLLOWING
1) You MUST override it in a MoneyMarket implementation.
2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function.
3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued.
4) You SHOULD look at how existing MoneyMarkets do it as an example.
*/
function _authorizeRescue(
address, /*token*/
address /*target*/
) internal view virtual override {
require(hasRole(RESCUER_ROLE, msg.sender), "MoneyMarket: not rescuer");
}
function _totalValue(uint256 currentIncomeIndex)
internal
view
virtual
returns (uint256);
function _incomeIndex() internal virtual returns (uint256 index);
event ESetParamAddress(
address indexed sender,
string indexed paramName,
address newValue
);
}
|
RESCUER_ROLE is managed by itself
|
function __MoneyMarket_init(address rescuer) internal initializer {
__Ownable_init();
__AccessControl_init();
_setupRole(RESCUER_ROLE, rescuer);
_setRoleAdmin(RESCUER_ROLE, RESCUER_ROLE);
}
| 2,535,479
|
./full_match/1/0x5061CDe874f75D119dE3B07E191644097343AB9E/sources/contracts/interfaces/IVault.sol
|
Governable.sol VaultAdmin.sol VaultCore.sol
|
interface IVault {
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event AssetAllocated(address _asset, address _strategy, uint256 _amount);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
function transferGovernance(address _newGovernor) external;
function claimGovernance() external;
function governor() external view returns (address);
function setPriceProvider(address _priceProvider) external;
function priceProvider() external view returns (address);
function setRedeemFeeBps(uint256 _redeemFeeBps) external;
function redeemFeeBps() external view returns (uint256);
function setVaultBuffer(uint256 _vaultBuffer) external;
function vaultBuffer() external view returns (uint256);
function setAutoAllocateThreshold(uint256 _threshold) external;
function autoAllocateThreshold() external view returns (uint256);
function setRebaseThreshold(uint256 _threshold) external;
function rebaseThreshold() external view returns (uint256);
function setStrategistAddr(address _address) external;
function strategistAddr() external view returns (address);
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external;
function maxSupplyDiff() external view returns (uint256);
function setTrusteeAddress(address _address) external;
function trusteeAddress() external view returns (address);
function setTrusteeFeeBps(uint256 _basis) external;
function trusteeFeeBps() external view returns (uint256);
function ousdMetaStrategy() external view returns (address);
function supportAsset(address _asset, uint8 _supportsAsset) external;
function approveStrategy(address _addr) external;
function removeStrategy(address _addr) external;
function setAssetDefaultStrategy(address _asset, address _strategy)
external;
function assetDefaultStrategies(address _asset)
external
view
returns (address);
function pauseRebase() external;
function unpauseRebase() external;
function rebasePaused() external view returns (bool);
function pauseCapital() external;
function unpauseCapital() external;
function capitalPaused() external view returns (bool);
function transferToken(address _asset, uint256 _amount) external;
function priceUnitMint(address asset) external view returns (uint256);
function priceUnitRedeem(address asset) external view returns (uint256);
function withdrawAllFromStrategy(address _strategyAddr) external;
function withdrawAllFromStrategies() external;
function withdrawFromStrategy(
address _strategyFromAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external;
function depositToStrategy(
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external;
function mint(
address _asset,
uint256 _amount,
uint256 _minimumOusdAmount
) external;
function mintForStrategy(uint256 _amount) external;
function redeem(uint256 _amount, uint256 _minimumUnitAmount) external;
function burnForStrategy(uint256 _amount) external;
function redeemAll(uint256 _minimumUnitAmount) external;
function allocate() external;
function rebase() external;
function totalValue() external view returns (uint256 value);
function checkBalance(address _asset) external view returns (uint256);
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory);
function getAssetCount() external view returns (uint256);
function getAssetConfig(address _asset)
external
view
returns (VaultStorage.Asset memory config);
function getAllAssets() external view returns (address[] memory);
function getStrategyCount() external view returns (uint256);
function getAllStrategies() external view returns (address[] memory);
function isSupportedAsset(address _asset) external view returns (bool);
function netOusdMintForStrategyThreshold() external view returns (uint256);
function setOusdMetaStrategy(address _ousdMetaStrategy) external;
function setNetOusdMintForStrategyThreshold(uint256 _threshold) external;
function netOusdMintedForStrategy() external view returns (int256);
pragma solidity ^0.8.0;
import { VaultStorage } from "../vault/VaultStorage.sol";
}
| 9,716,582
|
./full_match/73799/0x8048509982987E7ff65C9cf7C7C4997B0ffd3ce6/sources/contracts/dependencies/GreenproofManager.sol
|
unPause - when called, this function reverts the pausing and unlocks facet function executions only the contract admistrator is allowed to execute this unlocking function if the system is already unpaused, a call to this function will revert with `AlreadyUnpausedContract` error/
|
function unPause() external {
LibClaimManager.checkOwnership();
if (!isContractPaused) {
revert AlreadyUnpausedContract();
}
isContractPaused = false;
}
| 16,363,298
|
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Rollup.sol";
import "./facets/IRollupFacets.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IMessageProvider.sol";
import "./INode.sol";
import "../libraries/Cloneable.sol";
contract RollupEventBridge is IMessageProvider, Cloneable {
uint8 internal constant INITIALIZATION_MSG_TYPE = 11;
uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8;
uint8 internal constant CREATE_NODE_EVENT = 0;
uint8 internal constant CONFIRM_NODE_EVENT = 1;
uint8 internal constant REJECT_NODE_EVENT = 2;
uint8 internal constant STAKE_CREATED_EVENT = 3;
IBridge bridge;
address rollup;
modifier onlyRollup() {
require(msg.sender == rollup, "ONLY_ROLLUP");
_;
}
function initialize(address _bridge, address _rollup) external {
require(rollup == address(0), "ALREADY_INIT");
bridge = IBridge(_bridge);
rollup = _rollup;
}
function rollupInitialized(
uint256 confirmPeriodBlocks,
uint256 avmGasSpeedLimitPerBlock,
address owner,
bytes calldata extraConfig
) external onlyRollup {
bytes memory initMsg = abi.encodePacked(
keccak256("ChallengePeriodEthBlocks"),
confirmPeriodBlocks,
keccak256("SpeedLimitPerSecond"),
avmGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas
keccak256("ChainOwner"),
uint256(uint160(bytes20(owner))),
extraConfig
);
uint256 num = bridge.deliverMessageToInbox(
INITIALIZATION_MSG_TYPE,
address(0),
keccak256(initMsg)
);
emit InboxMessageDelivered(num, initMsg);
}
function nodeCreated(
uint256 nodeNum,
uint256 prev,
uint256 deadline,
address asserter
) external onlyRollup {
deliverToBridge(
abi.encodePacked(
CREATE_NODE_EVENT,
nodeNum,
prev,
block.number,
deadline,
uint256(uint160(bytes20(asserter)))
)
);
}
function nodeConfirmed(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum));
}
function nodeRejected(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum));
}
function stakeCreated(address staker, uint256 nodeNum) external onlyRollup {
deliverToBridge(
abi.encodePacked(
STAKE_CREATED_EVENT,
uint256(uint160(bytes20(staker))),
nodeNum,
block.number
)
);
}
function deliverToBridge(bytes memory message) private {
emit InboxMessageDelivered(
bridge.deliverMessageToInbox(
ROLLUP_PROTOCOL_EVENT_TYPE,
msg.sender,
keccak256(message)
),
message
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/proxy/Proxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RollupEventBridge.sol";
import "./RollupCore.sol";
import "./RollupLib.sol";
import "./INode.sol";
import "./INodeFactory.sol";
import "../challenge/IChallenge.sol";
import "../challenge/IChallengeFactory.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IOutbox.sol";
import "../bridge/Messages.sol";
import "../libraries/ProxyUtil.sol";
import "../libraries/Cloneable.sol";
import "./facets/IRollupFacets.sol";
abstract contract RollupBase is Cloneable, RollupCore, Pausable {
// Rollup Config
uint256 public confirmPeriodBlocks;
uint256 public extraChallengeTimeBlocks;
uint256 public avmGasSpeedLimitPerBlock;
uint256 public baseStake;
// Bridge is an IInbox and IOutbox
IBridge public delayedBridge;
ISequencerInbox public sequencerBridge;
IOutbox public outbox;
RollupEventBridge public rollupEventBridge;
IChallengeFactory public challengeFactory;
INodeFactory public nodeFactory;
address public owner;
address public stakeToken;
uint256 public minimumAssertionPeriod;
uint256 public STORAGE_GAP_1;
uint256 public STORAGE_GAP_2;
uint256 public challengeExecutionBisectionDegree;
address[] internal facets;
mapping(address => bool) isValidator;
/// @notice DEPRECATED -- this method is deprecated but still mantained for backward compatibility
/// @dev this actually returns the avmGasSpeedLimitPerBlock
/// @return this actually returns the avmGasSpeedLimitPerBlock
function arbGasSpeedLimitPerBlock() external view returns (uint256) {
return avmGasSpeedLimitPerBlock;
}
}
contract Rollup is Proxy, RollupBase {
using Address for address;
constructor(uint256 _confirmPeriodBlocks) public Cloneable() Pausable() {
// constructor is used so logic contract can't be init'ed
confirmPeriodBlocks = _confirmPeriodBlocks;
require(isInit(), "CONSTRUCTOR_NOT_INIT");
}
function isInit() internal view returns (bool) {
return confirmPeriodBlocks != 0;
}
// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ]
// connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]
function initialize(
bytes32 _machineHash,
uint256[4] calldata _rollupParams,
address _stakeToken,
address _owner,
bytes calldata _extraConfig,
address[6] calldata connectedContracts,
address[2] calldata _facets,
uint256[2] calldata sequencerInboxParams
) public {
require(!isInit(), "ALREADY_INIT");
// calls initialize method in user facet
require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT");
require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT");
(bool success, ) = _facets[1].delegatecall(
abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)
);
require(success, "FAIL_INIT_FACET");
delayedBridge = IBridge(connectedContracts[0]);
sequencerBridge = ISequencerInbox(connectedContracts[1]);
outbox = IOutbox(connectedContracts[2]);
delayedBridge.setOutbox(connectedContracts[2], true);
rollupEventBridge = RollupEventBridge(connectedContracts[3]);
delayedBridge.setInbox(connectedContracts[3], true);
rollupEventBridge.rollupInitialized(
_rollupParams[0],
_rollupParams[2],
_owner,
_extraConfig
);
challengeFactory = IChallengeFactory(connectedContracts[4]);
nodeFactory = INodeFactory(connectedContracts[5]);
INode node = createInitialNode(_machineHash);
initializeCore(node);
confirmPeriodBlocks = _rollupParams[0];
extraChallengeTimeBlocks = _rollupParams[1];
avmGasSpeedLimitPerBlock = _rollupParams[2];
baseStake = _rollupParams[3];
owner = _owner;
// A little over 15 minutes
minimumAssertionPeriod = 75;
challengeExecutionBisectionDegree = 400;
sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]);
// facets[0] == admin, facets[1] == user
facets = _facets;
emit RollupCreated(_machineHash);
require(isInit(), "INITIALIZE_NOT_INIT");
}
function postUpgradeInit() external {
// it is assumed the rollup contract is behind a Proxy controlled by a proxy admin
// this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// this upgrade moves the delay blocks and seconds tracking to the sequencer inbox
// because of that we need to update the admin facet logic to allow the owner to set
// these values in the sequencer inbox
STORAGE_GAP_1 = 0;
STORAGE_GAP_2 = 0;
}
function createInitialNode(bytes32 _machineHash) private returns (INode) {
bytes32 state = RollupLib.stateHash(
RollupLib.ExecutionState(
0, // total gas used
_machineHash,
0, // inbox count
0, // send count
0, // log count
0, // send acc
0, // log acc
block.number, // block proposed
1 // Initialization message already in inbox
)
);
return
INode(
nodeFactory.createNode(
state,
0, // challenge hash (not challengeable)
0, // confirm data
0, // prev node
block.number // deadline block (not challengeable)
)
);
}
/**
* This contract uses a dispatch pattern from EIP-2535: Diamonds
* together with Open Zeppelin's proxy
*/
function getFacets() external view returns (address, address) {
return (getAdminFacet(), getUserFacet());
}
function getAdminFacet() public view returns (address) {
return facets[0];
}
function getUserFacet() public view returns (address) {
return facets[1];
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual override returns (address) {
require(msg.data.length >= 4, "NO_FUNC_SIG");
address rollupOwner = owner;
// if there is an owner and it is the sender, delegate to admin facet
address target = rollupOwner != address(0) && rollupOwner == msg.sender
? getAdminFacet()
: getUserFacet();
require(target.isContract(), "TARGET_NOT_CONTRACT");
return target;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../INode.sol";
import "../../bridge/interfaces/IOutbox.sol";
interface IRollupUser {
function initialize(address _stakeToken) external;
function completeChallenge(address winningStaker, address losingStaker) external;
function returnOldDeposit(address stakerAddress) external;
function requireUnresolved(uint256 nodeNum) external view;
function requireUnresolvedExists() external view;
function countStakedZombies(INode node) external view returns (uint256);
}
interface IRollupAdmin {
event OwnerFunctionCalled(uint256 indexed id);
/**
* @notice Add a contract authorized to put messages into this rollup's inbox
* @param _outbox Outbox contract to add
*/
function setOutbox(IOutbox _outbox) external;
/**
* @notice Disable an old outbox from interacting with the bridge
* @param _outbox Outbox contract to remove
*/
function removeOldOutbox(address _outbox) external;
/**
* @notice Enable or disable an inbox contract
* @param _inbox Inbox contract to add or remove
* @param _enabled New status of inbox
*/
function setInbox(address _inbox, bool _enabled) external;
/**
* @notice Pause interaction with the rollup contract
*/
function pause() external;
/**
* @notice Resume interaction with the rollup contract
*/
function resume() external;
/**
* @notice Set the addresses of rollup logic facets called
* @param newAdminFacet address of logic that owner of rollup calls
* @param newUserFacet ddress of logic that user of rollup calls
*/
function setFacets(address newAdminFacet, address newUserFacet) external;
/**
* @notice Set the addresses of the validator whitelist
* @dev It is expected that both arrays are same length, and validator at
* position i corresponds to the value at position i
* @param _validator addresses to set in the whitelist
* @param _val value to set in the whitelist for corresponding address
*/
function setValidator(address[] memory _validator, bool[] memory _val) external;
/**
* @notice Set a new owner address for the rollup
* @param newOwner address of new rollup owner
*/
function setOwner(address newOwner) external;
/**
* @notice Set minimum assertion period for the rollup
* @param newPeriod new minimum period for assertions
*/
function setMinimumAssertionPeriod(uint256 newPeriod) external;
/**
* @notice Set number of blocks until a node is considered confirmed
* @param newConfirmPeriod new number of blocks until a node is confirmed
*/
function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external;
/**
* @notice Set number of extra blocks after a challenge
* @param newExtraTimeBlocks new number of blocks
*/
function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external;
/**
* @notice Set speed limit per block
* @param newAvmGasSpeedLimitPerBlock maximum avmgas to be used per block
*/
function setAvmGasSpeedLimitPerBlock(uint256 newAvmGasSpeedLimitPerBlock) external;
/**
* @notice Set base stake required for an assertion
* @param newBaseStake maximum avmgas to be used per block
*/
function setBaseStake(uint256 newBaseStake) external;
/**
* @notice Set the token used for stake, where address(0) == eth
* @dev Before changing the base stake token, you might need to change the
* implementation of the Rollup User facet!
* @param newStakeToken address of token used for staking
*/
function setStakeToken(address newStakeToken) external;
/**
* @notice Set max delay for sequencer inbox
* @param newSequencerInboxMaxDelayBlocks max number of blocks
* @param newSequencerInboxMaxDelaySeconds max number of seconds
*/
function setSequencerInboxMaxDelay(
uint256 newSequencerInboxMaxDelayBlocks,
uint256 newSequencerInboxMaxDelaySeconds
) external;
/**
* @notice Set execution bisection degree
* @param newChallengeExecutionBisectionDegree execution bisection degree
*/
function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree)
external;
/**
* @notice Updates a whitelist address for its consumers
* @dev setting the newWhitelist to address(0) disables it for consumers
* @param whitelist old whitelist to be deprecated
* @param newWhitelist new whitelist to be used
* @param targets whitelist consumers to be triggered
*/
function updateWhitelistConsumers(
address whitelist,
address newWhitelist,
address[] memory targets
) external;
/**
* @notice Updates a whitelist's entries
* @dev user at position i will be assigned value i
* @param whitelist whitelist to be updated
* @param user users to be updated in the whitelist
* @param val if user is or not allowed in the whitelist
*/
function setWhitelistEntries(
address whitelist,
address[] memory user,
bool[] memory val
) external;
/**
* @notice Updates whether an address is a sequencer at the sequencer inbox
* @param newSequencer address to be modified
* @param isSequencer whether this address should be authorized as a sequencer
*/
function setIsSequencer(address newSequencer, bool isSequencer) external;
/**
* @notice Upgrades the implementation of a beacon controlled by the rollup
* @param beacon address of beacon to be upgraded
* @param newImplementation new address of implementation
*/
function upgradeBeacon(address beacon, address newImplementation) external;
function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external;
function forceRefundStaker(address[] memory stacker) external;
function forceCreateNode(
bytes32 expectedNodeHash,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 prevNode
) external;
function forceConfirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IBridge {
event MessageDelivered(
uint256 indexed messageIndex,
bytes32 indexed beforeInboxAcc,
address inbox,
uint8 kind,
address sender,
bytes32 messageDataHash
);
event BridgeCallTriggered(
address indexed outbox,
address indexed destAddr,
uint256 amount,
bytes data
);
event InboxToggle(address indexed inbox, bool enabled);
event OutboxToggle(address indexed outbox, bool enabled);
function deliverMessageToInbox(
uint8 kind,
address sender,
bytes32 messageDataHash
) external payable returns (uint256);
function executeCall(
address destAddr,
uint256 amount,
bytes calldata data
) external returns (bool success, bytes memory returnData);
// These are only callable by the admin
function setInbox(address inbox, bool enabled) external;
function setOutbox(address inbox, bool enabled) external;
// View functions
function activeOutbox() external view returns (address);
function allowedInboxes(address inbox) external view returns (bool);
function allowedOutboxes(address outbox) external view returns (bool);
function inboxAccs(uint256 index) external view returns (bytes32);
function messageCount() external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IMessageProvider {
event InboxMessageDelivered(uint256 indexed messageNum, bytes data);
event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INode {
function initialize(
address _rollup,
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external;
function destroy() external;
function addStaker(address staker) external returns (uint256);
function removeStaker(address staker) external;
function childCreated(uint256) external;
function newChildConfirmDeadline(uint256 deadline) external;
function stateHash() external view returns (bytes32);
function challengeHash() external view returns (bytes32);
function confirmData() external view returns (bytes32);
function prev() external view returns (uint256);
function deadlineBlock() external view returns (uint256);
function noChildConfirmedBeforeBlock() external view returns (uint256);
function stakerCount() external view returns (uint256);
function stakers(address staker) external view returns (bool);
function firstChildBlock() external view returns (uint256);
function latestChildNumber() external view returns (uint256);
function requirePastDeadline() external view;
function requirePastChildConfirmDeadline() external view;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./ICloneable.sol";
contract Cloneable is ICloneable {
string private constant NOT_CLONE = "NOT_CLONE";
bool private isMasterCopy;
constructor() public {
isMasterCopy = true;
}
function isMaster() external view override returns (bool) {
return isMasterCopy;
}
function safeSelfDestruct(address payable dest) internal {
require(!isMasterCopy, NOT_CLONE);
selfdestruct(dest);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// 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);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
import "./IRollupCore.sol";
import "./RollupLib.sol";
import "./INodeFactory.sol";
import "./RollupEventBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract RollupCore is IRollupCore {
using SafeMath for uint256;
// Stakers become Zombies after losing a challenge
struct Zombie {
address stakerAddress;
uint256 latestStakedNode;
}
struct Staker {
uint256 index;
uint256 latestStakedNode;
uint256 amountStaked;
// currentChallenge is 0 if staker is not in a challenge
address currentChallenge;
bool isStaked;
}
uint256 private _latestConfirmed;
uint256 private _firstUnresolvedNode;
uint256 private _latestNodeCreated;
uint256 private _lastStakeBlock;
mapping(uint256 => INode) private _nodes;
mapping(uint256 => bytes32) private _nodeHashes;
address payable[] private _stakerList;
mapping(address => Staker) public override _stakerMap;
Zombie[] private _zombies;
mapping(address => uint256) private _withdrawableFunds;
/**
* @notice Get the address of the Node contract for the given node
* @param nodeNum Index of the node
* @return Address of the Node contract
*/
function getNode(uint256 nodeNum) public view override returns (INode) {
return _nodes[nodeNum];
}
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view override returns (address) {
return _stakerList[stakerNum];
}
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) public view override returns (bool) {
return _stakerMap[staker].isStaked;
}
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) public view override returns (uint256) {
return _stakerMap[staker].latestStakedNode;
}
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) public view override returns (address) {
return _stakerMap[staker].currentChallenge;
}
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) public view override returns (uint256) {
return _stakerMap[staker].amountStaked;
}
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) public view override returns (address) {
return _zombies[zombieNum].stakerAddress;
}
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) {
return _zombies[zombieNum].latestStakedNode;
}
/// @return Current number of un-removed zombies
function zombieCount() public view override returns (uint256) {
return _zombies.length;
}
function isZombie(address staker) public view override returns (bool) {
for (uint256 i = 0; i < _zombies.length; i++) {
if (staker == _zombies[i].stakerAddress) {
return true;
}
}
return false;
}
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view override returns (uint256) {
return _withdrawableFunds[owner];
}
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() public view override returns (uint256) {
return _firstUnresolvedNode;
}
/// @return Index of the latest confirmed node
function latestConfirmed() public view override returns (uint256) {
return _latestConfirmed;
}
/// @return Index of the latest rollup node created
function latestNodeCreated() public view override returns (uint256) {
return _latestNodeCreated;
}
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view override returns (uint256) {
return _lastStakeBlock;
}
/// @return Number of active stakers currently staked
function stakerCount() public view override returns (uint256) {
return _stakerList.length;
}
/**
* @notice Initialize the core with an initial node
* @param initialNode Initial node to start the chain with
*/
function initializeCore(INode initialNode) internal {
_nodes[0] = initialNode;
_firstUnresolvedNode = 1;
}
/**
* @notice React to a new node being created by storing it an incrementing the latest node counter
* @param node Node that was newly created
* @param nodeHash The hash of said node
*/
function nodeCreated(INode node, bytes32 nodeHash) internal {
_latestNodeCreated++;
_nodes[_latestNodeCreated] = node;
_nodeHashes[_latestNodeCreated] = nodeHash;
}
/// @return Node hash as of this node number
function getNodeHash(uint256 index) public view override returns (bytes32) {
return _nodeHashes[index];
}
/// @notice Reject the next unresolved node
function _rejectNextNode() internal {
destroyNode(_firstUnresolvedNode);
_firstUnresolvedNode++;
}
/// @notice Confirm the next unresolved node
function confirmNextNode(
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
confirmNode(
_firstUnresolvedNode,
beforeSendAcc,
sendsData,
sendLengths,
afterSendCount,
afterLogAcc,
afterLogCount,
outbox,
rollupEventBridge
);
}
function confirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
bytes32 afterSendAcc = RollupLib.feedAccumulator(sendsData, sendLengths, beforeSendAcc);
INode node = getNode(nodeNum);
// Authenticate data against node's confirm data pre-image
require(
node.confirmData() ==
RollupLib.confirmHash(
beforeSendAcc,
afterSendAcc,
afterLogAcc,
afterSendCount,
afterLogCount
),
"CONFIRM_DATA"
);
// trusted external call to outbox
outbox.processOutgoingMessages(sendsData, sendLengths);
destroyNode(_latestConfirmed);
_latestConfirmed = nodeNum;
_firstUnresolvedNode = nodeNum + 1;
rollupEventBridge.nodeConfirmed(nodeNum);
emit NodeConfirmed(nodeNum, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount);
}
/**
* @notice Create a new stake at latest confirmed node
* @param stakerAddress Address of the new staker
* @param depositAmount Stake amount of the new staker
*/
function createNewStake(address payable stakerAddress, uint256 depositAmount) internal {
uint256 stakerIndex = _stakerList.length;
_stakerList.push(stakerAddress);
_stakerMap[stakerAddress] = Staker(
stakerIndex,
_latestConfirmed,
depositAmount,
address(0), // new staker is not in challenge
true
);
_lastStakeBlock = block.number;
emit UserStakeUpdated(stakerAddress, 0, depositAmount);
}
/**
* @notice Check to see whether the two stakers are in the same challenge
* @param stakerAddress1 Address of the first staker
* @param stakerAddress2 Address of the second staker
* @return Address of the challenge that the two stakers are in
*/
function inChallenge(address stakerAddress1, address stakerAddress2)
internal
view
returns (address)
{
Staker storage staker1 = _stakerMap[stakerAddress1];
Staker storage staker2 = _stakerMap[stakerAddress2];
address challenge = staker1.currentChallenge;
require(challenge != address(0), "NO_CHAL");
require(challenge == staker2.currentChallenge, "DIFF_IN_CHAL");
return challenge;
}
/**
* @notice Make the given staker as not being in a challenge
* @param stakerAddress Address of the staker to remove from a challenge
*/
function clearChallenge(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
staker.currentChallenge = address(0);
}
/**
* @notice Mark both the given stakers as engaged in the challenge
* @param staker1 Address of the first staker
* @param staker2 Address of the second staker
* @param challenge Address of the challenge both stakers are now in
*/
function challengeStarted(
address staker1,
address staker2,
address challenge
) internal {
_stakerMap[staker1].currentChallenge = challenge;
_stakerMap[staker2].currentChallenge = challenge;
}
/**
* @notice Add to the stake of the given staker by the given amount
* @param stakerAddress Address of the staker to increase the stake of
* @param amountAdded Amount of stake to add to the staker
*/
function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
uint256 finalStaked = initialStaked.add(amountAdded);
staker.amountStaked = finalStaked;
emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);
}
/**
* @notice Reduce the stake of the given staker to the given target
* @param stakerAddress Address of the staker to reduce the stake of
* @param target Amount of stake to leave with the staker
* @return Amount of value released from the stake
*/
function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) {
Staker storage staker = _stakerMap[stakerAddress];
uint256 current = staker.amountStaked;
require(target <= current, "TOO_LITTLE_STAKE");
uint256 amountWithdrawn = current.sub(target);
staker.amountStaked = target;
increaseWithdrawableFunds(stakerAddress, amountWithdrawn);
emit UserStakeUpdated(stakerAddress, current, target);
return amountWithdrawn;
}
/**
* @notice Remove the given staker and turn them into a zombie
* @param stakerAddress Address of the staker to remove
*/
function turnIntoZombie(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
_zombies.push(Zombie(stakerAddress, staker.latestStakedNode));
deleteStaker(stakerAddress);
}
/**
* @notice Update the latest staked node of the zombie at the given index
* @param zombieNum Index of the zombie to move
* @param latest New latest node the zombie is staked on
*/
function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal {
_zombies[zombieNum].latestStakedNode = latest;
}
/**
* @notice Remove the zombie at the given index
* @param zombieNum Index of the zombie to remove
*/
function removeZombie(uint256 zombieNum) internal {
_zombies[zombieNum] = _zombies[_zombies.length - 1];
_zombies.pop();
}
/**
* @notice Remove the given staker and return their stake
* @param stakerAddress Address of the staker withdrawing their stake
*/
function withdrawStaker(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
increaseWithdrawableFunds(stakerAddress, initialStaked);
deleteStaker(stakerAddress);
emit UserStakeUpdated(stakerAddress, initialStaked, 0);
}
/**
* @notice Advance the given staker to the given node
* @param stakerAddress Address of the staker adding their stake
* @param nodeNum Index of the node to stake on
*/
function stakeOnNode(
address stakerAddress,
uint256 nodeNum,
uint256 confirmPeriodBlocks
) internal {
Staker storage staker = _stakerMap[stakerAddress];
INode node = _nodes[nodeNum];
uint256 newStakerCount = node.addStaker(stakerAddress);
staker.latestStakedNode = nodeNum;
if (newStakerCount == 1) {
INode parent = _nodes[node.prev()];
parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks));
}
}
/**
* @notice Clear the withdrawable funds for the given address
* @param owner Address of the account to remove funds from
* @return Amount of funds removed from account
*/
function withdrawFunds(address owner) internal returns (uint256) {
uint256 amount = _withdrawableFunds[owner];
_withdrawableFunds[owner] = 0;
emit UserWithdrawableFundsUpdated(owner, amount, 0);
return amount;
}
/**
* @notice Increase the withdrawable funds for the given address
* @param owner Address of the account to add withdrawable funds to
*/
function increaseWithdrawableFunds(address owner, uint256 amount) internal {
uint256 initialWithdrawable = _withdrawableFunds[owner];
uint256 finalWithdrawable = initialWithdrawable.add(amount);
_withdrawableFunds[owner] = finalWithdrawable;
emit UserWithdrawableFundsUpdated(owner, initialWithdrawable, finalWithdrawable);
}
/**
* @notice Remove the given staker
* @param stakerAddress Address of the staker to remove
*/
function deleteStaker(address stakerAddress) private {
Staker storage staker = _stakerMap[stakerAddress];
uint256 stakerIndex = staker.index;
_stakerList[stakerIndex] = _stakerList[_stakerList.length - 1];
_stakerMap[_stakerList[stakerIndex]].index = stakerIndex;
_stakerList.pop();
delete _stakerMap[stakerAddress];
}
/**
* @notice Destroy the given node and clear out its address
* @param nodeNum Index of the node to remove
*/
function destroyNode(uint256 nodeNum) internal {
_nodes[nodeNum].destroy();
_nodes[nodeNum] = INode(0);
}
function nodeDeadline(
uint256 avmGasSpeedLimitPerBlock,
uint256 gasUsed,
uint256 confirmPeriodBlocks,
INode prevNode
) internal view returns (uint256 deadlineBlock) {
// Set deadline rounding up to the nearest block
uint256 checkTime =
gasUsed.add(avmGasSpeedLimitPerBlock.sub(1)).div(avmGasSpeedLimitPerBlock);
deadlineBlock = max(block.number.add(confirmPeriodBlocks), prevNode.deadlineBlock()).add(
checkTime
);
uint256 olderSibling = prevNode.latestChildNumber();
if (olderSibling != 0) {
deadlineBlock = max(deadlineBlock, getNode(olderSibling).deadlineBlock());
}
return deadlineBlock;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
struct StakeOnNewNodeFrame {
uint256 currentInboxSize;
INode node;
bytes32 executionHash;
INode prevNode;
bytes32 lastHash;
bool hasSibling;
uint256 deadlineBlock;
uint256 gasUsed;
uint256 sequencerBatchEnd;
bytes32 sequencerBatchAcc;
}
struct CreateNodeDataFrame {
uint256 prevNode;
uint256 confirmPeriodBlocks;
uint256 avmGasSpeedLimitPerBlock;
ISequencerInbox sequencerInbox;
RollupEventBridge rollupEventBridge;
INodeFactory nodeFactory;
}
uint8 internal constant MAX_SEND_COUNT = 100;
function createNewNode(
RollupLib.Assertion memory assertion,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
CreateNodeDataFrame memory inputDataFrame,
bytes32 expectedNodeHash
) internal returns (bytes32 newNodeHash) {
StakeOnNewNodeFrame memory memoryFrame;
{
// validate data
memoryFrame.gasUsed = RollupLib.assertionGasUsed(assertion);
memoryFrame.prevNode = getNode(inputDataFrame.prevNode);
memoryFrame.currentInboxSize = inputDataFrame.sequencerInbox.messageCount();
// Make sure the previous state is correct against the node being built on
require(
RollupLib.stateHash(assertion.beforeState) == memoryFrame.prevNode.stateHash(),
"PREV_STATE_HASH"
);
// Ensure that the assertion doesn't read past the end of the current inbox
require(
assertion.afterState.inboxCount <= memoryFrame.currentInboxSize,
"INBOX_PAST_END"
);
// Insure inbox tip after assertion is included in a sequencer-inbox batch and return inbox acc; this gives replay protection against the state of the inbox
(memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc) = inputDataFrame
.sequencerInbox
.proveInboxContainsMessage(sequencerBatchProof, assertion.afterState.inboxCount);
}
{
memoryFrame.executionHash = RollupLib.executionHash(assertion);
memoryFrame.deadlineBlock = nodeDeadline(
inputDataFrame.avmGasSpeedLimitPerBlock,
memoryFrame.gasUsed,
inputDataFrame.confirmPeriodBlocks,
memoryFrame.prevNode
);
memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber() > 0;
// here we don't use ternacy operator to remain compatible with slither
if (memoryFrame.hasSibling) {
memoryFrame.lastHash = getNodeHash(memoryFrame.prevNode.latestChildNumber());
} else {
memoryFrame.lastHash = getNodeHash(inputDataFrame.prevNode);
}
memoryFrame.node = INode(
inputDataFrame.nodeFactory.createNode(
RollupLib.stateHash(assertion.afterState),
RollupLib.challengeRoot(assertion, memoryFrame.executionHash, block.number),
RollupLib.confirmHash(assertion),
inputDataFrame.prevNode,
memoryFrame.deadlineBlock
)
);
}
{
uint256 nodeNum = latestNodeCreated() + 1;
memoryFrame.prevNode.childCreated(nodeNum);
newNodeHash = RollupLib.nodeHash(
memoryFrame.hasSibling,
memoryFrame.lastHash,
memoryFrame.executionHash,
memoryFrame.sequencerBatchAcc
);
require(newNodeHash == expectedNodeHash, "UNEXPECTED_NODE_HASH");
nodeCreated(memoryFrame.node, newNodeHash);
inputDataFrame.rollupEventBridge.nodeCreated(
nodeNum,
inputDataFrame.prevNode,
memoryFrame.deadlineBlock,
msg.sender
);
}
emit NodeCreated(
latestNodeCreated(),
getNodeHash(inputDataFrame.prevNode),
newNodeHash,
memoryFrame.executionHash,
memoryFrame.currentInboxSize,
memoryFrame.sequencerBatchEnd,
memoryFrame.sequencerBatchAcc,
assertionBytes32Fields,
assertionIntFields
);
return newNodeHash;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../challenge/ChallengeLib.sol";
import "./INode.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library RollupLib {
using SafeMath for uint256;
struct Config {
bytes32 machineHash;
uint256 confirmPeriodBlocks;
uint256 extraChallengeTimeBlocks;
uint256 avmGasSpeedLimitPerBlock;
uint256 baseStake;
address stakeToken;
address owner;
address sequencer;
uint256 sequencerDelayBlocks;
uint256 sequencerDelaySeconds;
bytes extraConfig;
}
struct ExecutionState {
uint256 gasUsed;
bytes32 machineHash;
uint256 inboxCount;
uint256 sendCount;
uint256 logCount;
bytes32 sendAcc;
bytes32 logAcc;
uint256 proposedBlock;
uint256 inboxMaxCount;
}
function stateHash(ExecutionState memory execState) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
execState.gasUsed,
execState.machineHash,
execState.inboxCount,
execState.sendCount,
execState.logCount,
execState.sendAcc,
execState.logAcc,
execState.proposedBlock,
execState.inboxMaxCount
)
);
}
struct Assertion {
ExecutionState beforeState;
ExecutionState afterState;
}
function decodeExecutionState(
bytes32[3] memory bytes32Fields,
uint256[4] memory intFields,
uint256 proposedBlock,
uint256 inboxMaxCount
) internal pure returns (ExecutionState memory) {
return
ExecutionState(
intFields[0],
bytes32Fields[0],
intFields[1],
intFields[2],
intFields[3],
bytes32Fields[1],
bytes32Fields[2],
proposedBlock,
inboxMaxCount
);
}
function decodeAssertion(
bytes32[3][2] memory bytes32Fields,
uint256[4][2] memory intFields,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 inboxMaxCount
) internal view returns (Assertion memory) {
return
Assertion(
decodeExecutionState(
bytes32Fields[0],
intFields[0],
beforeProposedBlock,
beforeInboxMaxCount
),
decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount)
);
}
function executionStateChallengeHash(ExecutionState memory state)
internal
pure
returns (bytes32)
{
return
ChallengeLib.assertionHash(
state.gasUsed,
ChallengeLib.assertionRestHash(
state.inboxCount,
state.machineHash,
state.sendAcc,
state.sendCount,
state.logAcc,
state.logCount
)
);
}
function executionHash(Assertion memory assertion) internal pure returns (bytes32) {
return
ChallengeLib.bisectionChunkHash(
assertion.beforeState.gasUsed,
assertion.afterState.gasUsed - assertion.beforeState.gasUsed,
RollupLib.executionStateChallengeHash(assertion.beforeState),
RollupLib.executionStateChallengeHash(assertion.afterState)
);
}
function assertionGasUsed(RollupLib.Assertion memory assertion)
internal
pure
returns (uint256)
{
return assertion.afterState.gasUsed.sub(assertion.beforeState.gasUsed);
}
function challengeRoot(
Assertion memory assertion,
bytes32 assertionExecHash,
uint256 blockProposed
) internal pure returns (bytes32) {
return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount);
}
function challengeRootHash(
bytes32 execution,
uint256 proposedTime,
uint256 maxMessageCount
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount));
}
function confirmHash(Assertion memory assertion) internal pure returns (bytes32) {
return
confirmHash(
assertion.beforeState.sendAcc,
assertion.afterState.sendAcc,
assertion.afterState.logAcc,
assertion.afterState.sendCount,
assertion.afterState.logCount
);
}
function confirmHash(
bytes32 beforeSendAcc,
bytes32 afterSendAcc,
bytes32 afterLogAcc,
uint256 afterSendCount,
uint256 afterLogCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
beforeSendAcc,
afterSendAcc,
afterSendCount,
afterLogAcc,
afterLogCount
)
);
}
function feedAccumulator(
bytes memory messageData,
uint256[] memory messageLengths,
bytes32 beforeAcc
) internal pure returns (bytes32) {
uint256 offset = 0;
uint256 messageCount = messageLengths.length;
uint256 dataLength = messageData.length;
bytes32 messageAcc = beforeAcc;
for (uint256 i = 0; i < messageCount; i++) {
uint256 messageLength = messageLengths[i];
require(offset + messageLength <= dataLength, "DATA_OVERRUN");
bytes32 messageHash;
assembly {
messageHash := keccak256(add(messageData, add(offset, 32)), messageLength)
}
messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash));
offset += messageLength;
}
require(offset == dataLength, "DATA_LENGTH");
return messageAcc;
}
function nodeHash(
bool hasSibling,
bytes32 lastHash,
bytes32 assertionExecHash,
bytes32 inboxAcc
) internal pure returns (bytes32) {
uint8 hasSiblingInt = hasSibling ? 1 : 0;
return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INodeFactory {
function createNode(
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "../arch/IOneStepProof.sol";
interface IChallenge {
function initializeChallenge(
IOneStepProof[] calldata _executors,
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external;
function currentResponderTimeLeft() external view returns (uint256);
function lastMoveBlock() external view returns (uint256);
function timeout() external;
function asserter() external view returns (address);
function challenger() external view returns (address);
function clearChallenge() external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IChallengeFactory {
function createChallenge(
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IOutbox {
event OutboxEntryCreated(
uint256 indexed batchNum,
uint256 outboxEntryIndex,
bytes32 outputRoot,
uint256 numInBatch
);
event OutBoxTransactionExecuted(
address indexed destAddr,
address indexed l2Sender,
uint256 indexed outboxEntryIndex,
uint256 transactionIndex
);
function l2ToL1Sender() external view returns (address);
function l2ToL1Block() external view returns (uint256);
function l2ToL1EthBlock() external view returns (uint256);
function l2ToL1Timestamp() external view returns (uint256);
function l2ToL1BatchNum() external view returns (uint256);
function l2ToL1OutputId() external view returns (bytes32);
function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths)
external;
function outboxEntryExists(uint256 batchNum) external view returns (bool);
function executeTransaction(
uint256 outboxIndex,
bytes32[] calldata proof,
uint256 index,
address l2Sender,
address destAddr,
uint256 l2Block,
uint256 l1Block,
uint256 l2Timestamp,
uint256 amount,
bytes calldata calldataForL1) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library Messages {
function messageHash(
uint8 kind,
address sender,
uint256 blockNumber,
uint256 timestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
bytes32 messageDataHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
kind,
sender,
blockNumber,
timestamp,
inboxSeqNum,
gasPriceL1,
messageDataHash
)
);
}
function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(inbox, message));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library ProxyUtil {
function getProxyAdmin() internal view returns (address admin) {
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol#L48
// Storage slot with the admin of the proxy contract.
// This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
assembly {
admin := sload(slot)
}
}
}
// 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: Apache-2.0
/*
* Copyright 2019, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ICloneable {
function isMaster() external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
interface IRollupCore {
function _stakerMap(address stakerAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
bool
);
event RollupCreated(bytes32 machineHash);
event NodeCreated(
uint256 indexed nodeNum,
bytes32 indexed parentNodeHash,
bytes32 nodeHash,
bytes32 executionHash,
uint256 inboxMaxCount,
uint256 afterInboxBatchEndCount,
bytes32 afterInboxBatchAcc,
bytes32[3][2] assertionBytes32Fields,
uint256[4][2] assertionIntFields
);
event NodeConfirmed(
uint256 indexed nodeNum,
bytes32 afterSendAcc,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
);
event NodeRejected(uint256 indexed nodeNum);
event RollupChallengeStarted(
address indexed challengeContract,
address asserter,
address challenger,
uint256 challengedNode
);
event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance);
event UserWithdrawableFundsUpdated(
address indexed user,
uint256 initialBalance,
uint256 finalBalance
);
function getNode(uint256 nodeNum) external view returns (INode);
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view returns (address);
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) external view returns (bool);
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) external view returns (uint256);
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) external view returns (address);
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) external view returns (uint256);
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) external view returns (address);
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256);
/// @return Current number of un-removed zombies
function zombieCount() external view returns (uint256);
function isZombie(address staker) external view returns (bool);
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view returns (uint256);
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() external view returns (uint256);
/// @return Index of the latest confirmed node
function latestConfirmed() external view returns (uint256);
/// @return Index of the latest rollup node created
function latestNodeCreated() external view returns (uint256);
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view returns (uint256);
/// @return Number of active stakers currently staked
function stakerCount() external view returns (uint256);
/// @return Node hash as of this node number
function getNodeHash(uint256 index) external view returns (bytes32);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ISequencerInbox {
event SequencerBatchDelivered(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
bytes transactions,
uint256[] lengths,
uint256[] sectionsMetadata,
uint256 seqBatchIndex,
address sequencer
);
event SequencerBatchDeliveredFromOrigin(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
uint256 seqBatchIndex
);
event DelayedInboxForced(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
uint256 totalDelayedMessagesRead,
bytes32[2] afterAccAndDelayed,
uint256 seqBatchIndex
);
/// @notice DEPRECATED - look at IsSequencerUpdated for new updates
// event SequencerAddressUpdated(address newAddress);
event IsSequencerUpdated(address addr, bool isSequencer);
event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelayBlocksUpdated(uint256 newValue);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelaySecondsUpdated(uint256 newValue);
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external;
function setIsSequencer(address addr, bool isSequencer) external;
function messageCount() external view returns (uint256);
function maxDelayBlocks() external view returns (uint256);
function maxDelaySeconds() external view returns (uint256);
function inboxAccs(uint256 index) external view returns (bytes32);
function getInboxAccsLength() external view returns (uint256);
function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount)
external
view
returns (uint256, bytes32);
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view returns (address);
function isSequencer(address seq) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../libraries/MerkleLib.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library ChallengeLib {
using SafeMath for uint256;
function firstSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount + (totalCount % bisectionCount);
}
function otherSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount;
}
function bisectionChunkHash(
uint256 _segmentStart,
uint256 _segmentLength,
bytes32 _startHash,
bytes32 _endHash
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash));
}
function assertionHash(uint256 _avmGasUsed, bytes32 _restHash) internal pure returns (bytes32) {
// Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0)
return keccak256(abi.encodePacked(_avmGasUsed, _restHash));
}
function assertionRestHash(
uint256 _totalMessagesRead,
bytes32 _machineState,
bytes32 _sendAcc,
uint256 _sendCount,
bytes32 _logAcc,
uint256 _logCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
_totalMessagesRead,
_machineState,
_sendAcc,
_sendCount,
_logAcc,
_logCount
)
);
}
function updatedBisectionRoot(
bytes32[] memory _chainHashes,
uint256 _challengedSegmentStart,
uint256 _challengedSegmentLength
) internal pure returns (bytes32) {
uint256 bisectionCount = _chainHashes.length - 1;
bytes32[] memory hashes = new bytes32[](bisectionCount);
uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount);
uint256 segmentStart = _challengedSegmentStart;
hashes[0] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[0],
_chainHashes[1]
);
segmentStart = segmentStart.add(chunkSize);
chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount);
for (uint256 i = 1; i < bisectionCount; i++) {
hashes[i] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[i],
_chainHashes[i + 1]
);
segmentStart = segmentStart.add(chunkSize);
}
return MerkleLib.generateRoot(hashes);
}
function verifySegmentProof(
bytes32 challengeState,
bytes32 item,
bytes32[] calldata _merkleNodes,
uint256 _merkleRoute
) internal pure returns (bool) {
return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library MerkleLib {
function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) {
bytes32[] memory prevLayer = _hashes;
while (prevLayer.length > 1) {
bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2);
for (uint256 i = 0; i < nextLayer.length; i++) {
if (2 * i + 1 < prevLayer.length) {
nextLayer[i] = keccak256(
abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1])
);
} else {
nextLayer[i] = prevLayer[2 * i];
}
}
prevLayer = nextLayer;
}
return prevLayer[0];
}
function calculateRoot(
bytes32[] memory nodes,
uint256 route,
bytes32 item
) internal pure returns (bytes32) {
uint256 proofItems = nodes.length;
require(proofItems <= 256);
bytes32 h = item;
for (uint256 i = 0; i < proofItems; i++) {
if (route % 2 == 0) {
h = keccak256(abi.encodePacked(nodes[i], h));
} else {
h = keccak256(abi.encodePacked(h, nodes[i]));
}
route /= 2;
}
return h;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IOneStepProof {
// Bridges is sequencer bridge then delayed bridge
function executeStep(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
)
external
view
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
);
function executeStepDebug(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
) external view returns (string memory startMachine, string memory afterMachine);
}
|
Get the address of the staker at the given index stakerNum Index of the staker return Address of the staker/
|
function getStakerAddress(uint256 stakerNum) external view override returns (address) {
return _stakerList[stakerNum];
}
| 577,846
|
./full_match/42/0xe0Ab69528526a07c03335B64487cFD5fD7273501/sources/index.sol
|
Trident pool interface.
|
interface IPool {
function swap(bytes calldata data) external returns (uint256 finalAmountOut);
function flashSwap(bytes calldata data) external returns (uint256 finalAmountOut);
function mint(bytes calldata data) external returns (uint256 liquidity);
function burn(bytes calldata data) external returns (TokenAmount[] memory withdrawnAmounts);
function burnSingle(bytes calldata data) external returns (uint256 amountOut);
function poolIdentifier() external pure returns (bytes32);
function getAssets() external view returns (address[] memory);
function getAmountOut(bytes calldata data) external view returns (uint256 finalAmountOut);
event Swap(
address indexed recipient,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
struct TokenAmount {
address token;
uint256 amount;
}
}
| 9,572,363
|
./full_match/80001/0xAD552CCAEe30f72E44bb557F058Ceb95fcEE5a3F/sources/project_/contracts/extensions/token-uri/BaseURIUpgradeable.sol
|
Base uri for generate full token uri baseURI Init value for `_baseURI`
|
function __BaseURI_init(string memory baseURI) internal {
_setBaseURI(baseURI);
}
| 9,450,964
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.